Coverage for src/renaissance/syntax_tree/ast_refactor_actions.py: 88%
60 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
1# Copyright (C) 2024-2026 TNO
2#
3# Licensed under the terms specified in the LICENSE file in the root directory
4# of this repository, also available at:
5# https://github.com/TNO/Renaissance.Py/blob/main/LICENSE
7"""AI: Higher-level refactoring actions built on top of pattern matching and rewriting."""
9from collections.abc import Callable, Sequence
10from functools import cache
11from typing import TYPE_CHECKING
13from renaissance.syntax_tree.ast_finder import matches_node
14from renaissance.syntax_tree.ast_node import ASTNode
15from renaissance.syntax_tree.ast_processor import ASTProcessor
16from renaissance.syntax_tree.match_finder import MatchFinder, PatternMatch
17from renaissance.syntax_tree.semantic_kind import SemanticKind
19# TODO(FrancescoPezzella): Replace with a lazy import in Python 3.15.
20# https://github.com/TNO/Renaissance.Py/issues/275
21if TYPE_CHECKING:
22 from renaissance.integrations.clang.c_pattern_factory import CPPPatternFactory
25def _kind_predicate(kind):
26 if kind is None:
27 return lambda _node: False
28 if callable(kind):
29 return kind
30 if isinstance(kind, SemanticKind):
31 return lambda node: node.semantic_kind is kind
32 raise TypeError("kind must be a SemanticKind or a node predicate")
35class ASTRefactorActions:
36 """AI: Higher-level refactoring actions (replace, insert, remove) built on top of pattern matching and rewriting."""
38 def __init__(self, processor: ASTProcessor, pattern_factory: CPPPatternFactory) -> None:
39 """AI: Provide pattern-based refactoring actions (replace, insert, remove) over an AST."""
40 self.processor = processor
41 self.pattern_factory = pattern_factory
42 self.replaced: set[int] = set()
44 def replace_expr(self, name: str, replacement: str, kind: SemanticKind | Callable[[ASTNode], bool]) -> None:
45 """AI: Replace occurrences of the named expression matching kind with replacement."""
46 kind_predicate = _kind_predicate(kind)
48 def test(n: ASTNode):
49 if (kind and matches_node(n, kind_predicate)) and n.name == name:
50 yield n
52 [self.processor.replace(found.text.replace(found.name, replacement, 1), found) for found in self.processor.find_all(test)]
54 def replace_name(
55 self,
56 name: str,
57 replacement: str,
58 kind: SemanticKind | Callable[[ASTNode], bool] | None = None,
59 skip_kind: SemanticKind | Callable[[ASTNode], bool] | None = None,
60 ) -> None:
61 """AI: Replace occurrences of the named node (matching kind, excluding skip_kind) with replacement."""
62 kind_predicate = _kind_predicate(kind)
63 skip_kind_predicate = _kind_predicate(skip_kind)
65 def matches_name(n1: ASTNode) -> bool:
66 return (
67 (kind is None or matches_node(n1, kind_predicate))
68 and (skip_kind is None or not matches_node(n1, skip_kind_predicate))
69 and n1
70 and n1.name == name
71 )
73 found_nodes = self.processor.find_all(matches_name)
74 [self.replaced.add(found.offset) for found in found_nodes if found.offset not in self.replaced]
75 for n in found_nodes:
76 self.processor.replace(n.text.replace(n.name, replacement, 1), n)
78 def replace_text(
79 self,
80 text: str,
81 replacement: str,
82 kind: SemanticKind | Callable[[ASTNode], bool] | None = None,
83 skip_kind: SemanticKind | Callable[[ASTNode], bool] | None = None,
84 ) -> None:
85 """AI: Replace nodes whose text equals text (matching kind, excluding skip_kind) with replacement."""
86 kind_predicate = _kind_predicate(kind)
87 skip_kind_predicate = _kind_predicate(skip_kind)
89 def matches_text(n: ASTNode) -> bool:
90 return (
91 (kind is None or matches_node(n, kind_predicate))
92 and (skip_kind is None or not matches_node(n, skip_kind_predicate))
93 and n is not None
94 and n.text == text
95 )
97 found_nodes = self.processor.find_all(matches_text)
98 [self.replaced.add(found.offset) for found in found_nodes if found.offset not in self.replaced]
100 [self.processor.replace(n.text.replace(n.name, replacement, 1), n) for n in found_nodes]
102 def replace_declaration(self, declaration: str, replacement: str) -> None:
103 """AI: Replace every match of declaration with replacement."""
104 for match in self.find_declaration(declaration):
105 self.processor.replace(replacement, match)
107 def _replace_patterns(
108 self,
109 node: ASTNode,
110 replacement: str,
111 patterns: Sequence[Sequence[ASTNode]],
112 matches: Sequence[PatternMatch],
113 ) -> None:
114 if not patterns:
115 self.processor.replace(replacement, matches)
116 return
117 [
118 self._replace_patterns(m.nodes[0], replacement, patterns[1:], list(matches) + [m])
119 for m in MatchFinder.find_all([node], patterns[0])
120 ]
122 @cache
123 def find_declaration(self, decl_pattern: str):
124 """AI: Return the matches of decl_pattern parsed as a declaration pattern."""
125 pattern = self.pattern_factory.create_declaration(decl_pattern)
126 return self.processor.find_match(pattern)
128 @cache
129 def collect(self, pattern: str, pattern_kind: str):
130 """AI: Return the matches of pattern parsed as the given pattern_kind."""
131 root = self.pattern_factory.create(pattern, pattern_kind)
133 return self.processor.find_match(root)