尝试在 Smalltalk VisualWorks 中的所有类中搜索字符串



我正在尝试创建一个小函数来搜索整个应用程序中的字符串。

我得到了这个代码,但它没有多大帮助

aString := '\'.
class := DosFileDirectory.
methodsContainingString := class methodDictionary values select: [:method |
    method hasLiteralSuchThat: [:lit |
        (lit isString and: [lit isSymbol not]) and:
            [lit = aString]]].
messageList := methodsContainingString collect: [ :e | MethodReference new setStandardClass: class methodSymbol: e selector ].
SystemNavigation new
    browseMessageList: messageList
    name: 'methods containing string'.

最简单的方法是直接使用 MethodCollector(请参阅 MethodCollector>>methodsSelect:)

| mc pattern |
pattern := '*',searchString,'*'. 
mc := MethodCollector new. 
mc browseSelect: (mc methodsSelect: [:m | pattern match: m getSource]).

MethodCollector 已经负责遍历方法,无需自己动手。MethodCollector 还定义了组合查询的方法,因此您还可以将查询限制为特定包中的方法。

要搜索整个源代码,您可以执行以下操作

searchAll := [ :searchedString |
    (Object withAllSubclasses collect: [ :cls |
        cls methodDictionary values select: [ :method |
            (method getSource findString: searchedString startingAt: 1) > 0
        ]
    ]) inject: #() into: [ :arr :each | arr, each ]
]
  • Object withAllSubclasses将选择系统中的所有类
  • method getSource findString:startingAt: 将自己进行匹配(您可以用正则表达式等替换它)
  • #inject:into:将扁平化数组(否则它是一个数组数组)

要执行搜索,请评估块:

matchedMethods := searchAll value: 'Answer a Paragraph' "(returns a collection of methods containing the string)"

最后,您可以检查集合,或在浏览器中打开它:

MethodCollector new
    openListBrowserOn: (matchedMethods collect: [ :each | each definition ])
    label: 'methods containing "Answer a Paragraph"'

最新更新