在 Pharo Smalltalk 中重构方法并创建具有不同名称的副本?
Refactoring methods and creating copies with a different name in Pharo Smalltalk?
我正在尝试重构和一些自定义功能。有没有办法将方法复制到与原始方法相同的 class 但使用新名称? (本质上是创建一个非常浅的副本)您可以通过编辑方法源代码手动完成此操作,但可以通过编程方式完成吗?
例如:
doMethodName: anArgument
^ anObject doThat with: anArgument
变成:
doNewMethodName: anArgument
^ anObject doThat with: anArgument
您可以通过向目标 class 发送 compile:
消息来编译方法。
- 检索方法
- 例如
method := Float>>#cos
或 method := Float methodNamed: #cos
获取源代码
method sourceCode
将 return 方法代码作为字符串
method ast
(或method parseTree
)将return代码作为解析树表示
将代码编译成class(可选协议)
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
return 将代码作为字符串,这不是最好的操作方式。
如果你只是想改变方法名,你可以在 AST 中重命名它,例如
tree := (Something>>#doMethodName:) parseTree.
tree selector: 'doNewerMethodName:'.
Something compile: tree newSource.
我正在尝试重构和一些自定义功能。有没有办法将方法复制到与原始方法相同的 class 但使用新名称? (本质上是创建一个非常浅的副本)您可以通过编辑方法源代码手动完成此操作,但可以通过编程方式完成吗?
例如:
doMethodName: anArgument
^ anObject doThat with: anArgument
变成:
doNewMethodName: anArgument
^ anObject doThat with: anArgument
您可以通过向目标 class 发送 compile:
消息来编译方法。
- 检索方法
- 例如
method := Float>>#cos
或method := Float methodNamed: #cos
- 例如
获取源代码
method sourceCode
将 return 方法代码作为字符串method ast
(或method parseTree
)将return代码作为解析树表示
将代码编译成class(可选协议)
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
return 将代码作为字符串,这不是最好的操作方式。
如果你只是想改变方法名,你可以在 AST 中重命名它,例如
tree := (Something>>#doMethodName:) parseTree.
tree selector: 'doNewerMethodName:'.
Something compile: tree newSource.