Coverage for src / rejuvenation / python_cst_example.py: 80%
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
1import textwrap
3from rejuvenation.python_lst_example import python_lst_smoke_test
4from renaissance.integrations.python.ast.cst_node import PythonCstNode
5from renaissance.integrations.python.ast.factory import PythonFactory, PythonPatternFactory
6from renaissance.integrations.types import Call
7from renaissance.syntax_tree import ASTRewriter, ASTShower
8from renaissance.syntax_tree.ast_finder import find_ast_type
9from renaissance.syntax_tree.match_finder import match_pattern
11example_code = """
12from module import foo, bar, baz, quux
13ba(51)
14na(52)
15na(53)
16pa(54)
17if pa():
18 ba()
19pa(54)
20"""
23def python_cst_smoke_test():
25 # adapter = TreeSitterAdapter(tree_sitter_python)
26 # tree = adapter.parse_code(code)
27 # lst = adapter.to_lst(code, tree)
29 factory = PythonFactory(PythonCstNode)
30 pattern_factory = PythonPatternFactory(factory)
32 atu = factory.create_from_text(example_code, "example.py")
34 pattern1 = pattern_factory.create_statement("if pa(): $$stmts")
35 pattern2 = pattern_factory.create_expression("na($a)")
37 print("_______________pattern 1____________________________________")
38 ASTShower.show_node(pattern1.node, include_properties=True)
39 print("_______________pattern 1____________________________________")
40 ASTShower.show_node(pattern2.node, include_properties=False)
41 print("_______________ast____________________________________")
42 ASTShower.focus = "ba"
43 ASTShower.show_node(atu)
45 print("_______________simple find____________________________________")
46 nodes = find_ast_type(atu, Call)
48 ASTShower.show_node(nodes[0])
50 pattern1replacement = textwrap.dedent("""
51 # changed if expr to const
52 isAOne=True
53 if(isAOne):
54 $$stmts
55 """)
56 pattern2replacement = "# changed function f1 to f2\nf2($a,123456)\n"
58 rewriter = ASTRewriter(atu)
60 for match in match_pattern(atu.children, [pattern1]):
61 refactor(match, pattern1replacement, rewriter)
63 for match in match_pattern(atu.children, [pattern2]):
64 refactor(match, pattern2replacement, rewriter)
66 return rewriter.apply_to_string()
69def refactor(match, replacement_text, rewriter):
70 for placeholder in match.expansions:
71 replacement_text = replacement_text.replace(placeholder, match[placeholder])
72 return rewriter.replace(replacement_text, match.nodes)
75if __name__ == "__main__":
76 result = python_lst_smoke_test()
77 print("_______________end result_________________________________")
78 print(result)