重构方法并在Pharo Smalltalk中创建具有不同名称的副本



我正在尝试重构和一些自定义功能。有没有办法将方法复制到与原始方法相同的类,但使用新名称?(本质上创建一个非常浅的副本)您可以通过编辑方法源手动执行此操作,但可以通过编程方式完成吗?

例如:

doMethodName: anArgument
^ anObject doThat with: anArgument

成为:

doNewMethodName: anArgument
^ anObject doThat with: anArgument

可以通过向目标类发送compile:消息来编译方法。

  1. 检索方法
    • 例如 method := Float>>#cosmethod := Float methodNamed: #cos
  2. 检索源代码

    • method sourceCode 将以字符串形式返回方法代码
    • method ast(或method parseTree)将返回代码作为解析的树表示形式
  3. 代码编译为类(可选使用协议)

    • TargetClass compile: sourceCode
    • TargetClass compile: sourceCode classified: protocol

所以如果你有

Something>>doMethodName: anArgument
    ^ anObject doThat with: anArgument

你可以做

code := (Something>>#doMethodName:) sourceCode.
"replace all matches"
newCode := code copyReplaceAll: 'doMethodName:' with: 'doNewMethodName:'.
"or just the first"
newCode := code copyWithRegex: '^doMethodName:' matchesReplacedWith: 'doNewMethodName:'.
Something compile: newCode.

使用 AST

sourceCode 将代码作为字符串返回,这不是最好的操作方式。如果您只想更改方法名称,则可以在 AST 中重命名它,例如

tree := (Something>>#doMethodName:) parseTree.
tree selector: 'doNewerMethodName:'.
Something compile: tree newSource.

最新更新