Coverage for src/rejuvenation/python_lst_example.py: 92%
40 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 tree-sitter LST-based rewriting of Python source."""
3import textwrap
5from renaissance.integrations.python.ast.factory import PythonFactory, PythonPatternFactory
6from renaissance.integrations.tree_sitter.lst import LSTNode
7from renaissance.syntax_tree import ASTRewriter, ASTShower
8from renaissance.syntax_tree.ast_finder import find_semantic_kind
9from renaissance.syntax_tree.match_finder import match_pattern
10from renaissance.syntax_tree.semantic_kind import SemanticKind
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_lst_smoke_test():
25 """AI: Demonstrate matching and rewriting `example_code` using the tree-sitter LST integration."""
26 # adapter = TreeSitterAdapter(tree_sitter_python)
27 # tree = adapter.parse_code(code)
28 # lst = adapter.to_lst(code, tree)
30 factory = PythonFactory(LSTNode)
31 pattern_factory = PythonPatternFactory(factory)
33 atu = factory.create_from_text(example_code, "example.py")
35 pattern1 = pattern_factory.create_statement("if pa(): $$stmts")
36 pattern2 = pattern_factory.create_expression("na($a)")
38 print("_______________pattern 1____________________________________")
39 ASTShower.show_node(pattern1.node, include_properties=True)
40 print("_______________pattern 1____________________________________")
41 ASTShower.show_node(pattern2.node, include_properties=False)
42 print("_______________ast____________________________________")
43 ASTShower.focus = "ba"
44 ASTShower.show_node(atu)
46 print("_______________simple find____________________________________")
47 nodes = find_semantic_kind(atu, SemanticKind.CALL)
49 ASTShower.show_node(nodes[0])
51 pattern1replacement = textwrap.dedent("""
52 # changed if expr to const
53 isAOne=True
54 if(isAOne):
55 $$stmts
56 """)
57 pattern2replacement = "# changed function f1 to f2\nf2($a,123456)\n"
59 rewriter = ASTRewriter(atu)
61 for match in match_pattern(atu.children, [pattern1]):
62 refactor(match, pattern1replacement, rewriter)
64 for match in match_pattern(atu.children, [pattern2]):
65 refactor(match, pattern2replacement, rewriter)
67 return rewriter.apply_to_string()
70def refactor(match, replacement_text, rewriter):
71 """AI: Expand placeholders in `replacement_text` from `match` and queue the rewrite."""
72 for placeholder in match.expansions:
73 replacement_text = replacement_text.replace(placeholder, match[placeholder])
74 return rewriter.replace(replacement_text, match.nodes)
77if __name__ == "__main__":
78 result = python_lst_smoke_test()
79 print("_______________end result_________________________________")
80 print(result)