Coverage for src / rejuvenation / python_rst_example.py: 93%
41 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-09-09 14:04 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-09-09 14:04 +0000
1# This script demonstrates the use of the syntax_tree library to parse and rewrite Python code.
2# It specifically showcases nested replacements and multiple patterns.
3import textwrap
5from renaissance.integrations.python.ast.factory import PythonFactory, PythonPatternFactory
6from renaissance.integrations.python.ast.rst_node import PythonRstNode
7from renaissance.integrations.types import Call
8from renaissance.syntax_tree import ASTRewriter, ASTShower
9from renaissance.syntax_tree.ast_finder import find_ast_type
10from renaissance.syntax_tree.match_finder import match_pattern
12example_code = """
13from module import foo, bar, baz, quux
14ba(51)
15na(52)
16na(53)
17pa(54)
18if pa():
19 ba()
20pa(54)
21"""
24def python_rst_smoke_test():
25 atu: PythonRstNode = PythonRstNode.load_from_text(example_code)
27 factory = PythonFactory(PythonRstNode)
28 pattern_factory = PythonPatternFactory(factory)
30 atu = factory.create_from_text(example_code, "example.py")
32 pattern1 = pattern_factory.create_statement("if pa(): $$stmts")
33 pattern2 = pattern_factory.create_expression("na($a)")
35 print("_______________pattern 1____________________________________")
36 ASTShower.show_node(pattern1.node, include_properties=True)
37 print("_______________pattern 1____________________________________")
38 ASTShower.show_node(pattern2.node, include_properties=False)
39 print("_______________ast____________________________________")
40 ASTShower.focus = "ba"
41 ASTShower.show_node(atu)
43 print("_______________simple find____________________________________")
44 nodes = find_ast_type(atu, Call)
46 ASTShower.show_node(nodes[0])
48 pattern1replacement = textwrap.dedent("""
49 # changed if expr to const
50 isAOne=True
51 if(isAOne):
52 $$stmts
53 """)
54 pattern2replacement = "# changed function f1 to f2\nf2($a,123456)\n"
56 rewriter = ASTRewriter(atu)
58 for match in match_pattern(atu.body, [pattern1]):
59 refactor(match, pattern1replacement, rewriter)
61 for match in match_pattern(atu.body, [pattern2]):
62 refactor(match, pattern2replacement, rewriter)
64 return rewriter.apply_to_string()
67def refactor(match, replacement_text, rewriter):
68 for placeholder in match.expansions:
69 replacement_text = replacement_text.replace(placeholder, match[placeholder])
70 return rewriter.replace(replacement_text, match.nodes)
73if __name__ == "__main__":
74 result = python_rst_smoke_test()
75 print("_______________end result_________________________________")
76 print(result)