Coverage for src/rejuvenation/python_cst_example.py: 80%
41 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-02 13:12 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-02 13:12 +0000
1"""AI: Example script demonstrating CST-based rewriting of Python source."""
3import textwrap
5from rejuvenation.python_lst_example import python_lst_smoke_test
6from renaissance.integrations.python.ast.cst_node import PythonCstNode
7from renaissance.integrations.python.ast.factory import PythonFactory, PythonPatternFactory
8from renaissance.syntax_tree import ASTRewriter, ASTShower
9from renaissance.syntax_tree.ast_finder import find_semantic_kind
10from renaissance.syntax_tree.match_finder import match_pattern
11from renaissance.syntax_tree.semantic_kind import SemanticKind
13example_code = """
14from module import foo, bar, baz, quux
15ba(51)
16na(52)
17na(53)
18pa(54)
19if pa():
20 ba()
21pa(54)
22"""
25def python_cst_smoke_test():
26 """AI: Demonstrate matching and rewriting `example_code` using the CST integration."""
27 # adapter = TreeSitterAdapter(tree_sitter_python)
28 # tree = adapter.parse_code(code)
29 # lst = adapter.to_lst(code, tree)
31 factory = PythonFactory(PythonCstNode)
32 pattern_factory = PythonPatternFactory(factory)
34 atu = factory.create_from_text(example_code, "example.py")
36 pattern1 = pattern_factory.create_statement("if pa(): $$stmts")
37 pattern2 = pattern_factory.create_expression("na($a)")
39 print("_______________pattern 1____________________________________")
40 ASTShower.show_node(pattern1.node, include_properties=True)
41 print("_______________pattern 1____________________________________")
42 ASTShower.show_node(pattern2.node, include_properties=False)
43 print("_______________ast____________________________________")
44 ASTShower.focus = "ba"
45 ASTShower.show_node(atu)
47 print("_______________simple find____________________________________")
48 nodes = find_semantic_kind(atu, SemanticKind.CALL)
50 ASTShower.show_node(nodes[0])
52 pattern1replacement = textwrap.dedent("""
53 # changed if expr to const
54 isAOne=True
55 if(isAOne):
56 $$stmts
57 """)
58 pattern2replacement = "# changed function f1 to f2\nf2($a,123456)\n"
60 rewriter = ASTRewriter(atu)
62 for match in match_pattern(atu.children, [pattern1]):
63 refactor(match, pattern1replacement, rewriter)
65 for match in match_pattern(atu.children, [pattern2]):
66 refactor(match, pattern2replacement, rewriter)
68 return rewriter.apply_to_string()
71def refactor(match, replacement_text, rewriter):
72 """AI: Expand placeholders in `replacement_text` from `match` and queue the rewrite."""
73 for placeholder in match.expansions:
74 replacement_text = replacement_text.replace(placeholder, match[placeholder])
75 return rewriter.replace(replacement_text, match.nodes)
78if __name__ == "__main__":
79 result = python_lst_smoke_test()
80 print("_______________end result_________________________________")
81 print(result)