基于AST的片段化源代码重构工具包
项目描述
重构
简单、无烦恼、无依赖、基于AST的片段化源代码重构和转换工具包。
为什么?
我们的框架主要基于“简单但有效”的转换原则。我们专注于针对源代码小段落的重构,并由此展开。这使得我们能够直接对分析和转换的单个格式进行操作。这是我们与其他类似工具相比的优势所在。
如何?
我们不多谈细节,但为了给您一个预览,我们可以尝试编写一个规则,将标识符placeholder
替换为42
。
import ast
from refactor import Rule, Replace, run
# Each refactor transformer inherits from "refactor.Rule"
class FillPlaceholders(Rule):
# And each rule implements a "match()" method, which would
# receive every node in the tree in a breadth-first order.
def match(self, node: ast.AST) -> Replace:
# This is where things get interesting. Instead of just writing
# filters with if statements, you can use the following assert
# based approach (a contract of transformation).
# For this case, our contract is going to be: if the given node
# is an identifier with the name of "placeholder", it will be
# replaced with literal "42".
assert isinstance(node, ast.Name)
assert node.id == "placeholder"
# And this is where we choose what action we are taking for the
# given node (which we have verified with our contract). There
# are multiple transformation actions, but in this case what we
# need is something that replaces a node with another one.
replacement = ast.Constant(42)
return Replace(node, replacement)
if __name__ == "__main__":
# And finally in here, we just use the default CLI that comes
# bundled with refactor. When provided with a bunch of rules,
# it creates a simple interface that can process given files
# show the diff for changes and even apply them.
run(rules=[FillPlaceholders])
如果我们在一个文件上运行上述规则,我们可以看到它的表现
--- test_file.py
+++ test_file.py
@@ -1,11 +1,11 @@
def main():
- print(placeholder * 3 + 2)
+ print(42 * 3 + 2)
- print(2 + placeholder + 3)
+ print(2 + 42 + 3)
# some comments
- placeholder # maybe other comments
+ 42 # maybe other comments
if something:
other_thing
- print(placeholder)
+ print(42)
if __name__ == "__main__":
main()
想了解更多,请查看我们的 文档!
项目详情
下载文件
下载适用于您平台的文件。如果您不确定该选择哪个,请了解有关安装包的更多信息。
源代码分发
refactor-0.6.3.tar.gz (25.0 kB 查看哈希值)
构建分发
refactor-0.6.3-py3-none-any.whl (29.4 kB 查看哈希值)
关闭
refactor-0.6.3.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 165f969522894ab4db7e14fe5408d7c664b0d36a208b76aa3d8e1898beb07d5f |
|
MD5 | 74bb29462e6ce5c352eea99e6a450aa1 |
|
BLAKE2b-256 | 831d19247d5781c076a00932438a620a18bdc41d62a0783bf43deba9098828be |
关闭
refactor-0.6.3-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | c9b8a1622c93727c81958aef43fe9293f6d61c27c1bc8742f69f460a8bf33622 |
|
MD5 | 13e691d04f9bf434131d33c72b770b93 |
|
BLAKE2b-256 | c5b73bed70c569f19161744b2d5e1768e33552af499bd863759453f49633efe4 |