Coverage for src/renaissance/utils/ast_utils.py: 95%

64 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-02 13:12 +0000

1"""AI: Low-level AST utility helpers: sibling lookup, placeholder handling, and node matching.""" 

2 

3from collections import deque 

4from contextlib import contextmanager 

5from contextvars import ContextVar 

6 

7from renaissance.integrations import MATCH_ALL, MATCH_ONE 

8 

9DISPLAY_PARSER_KIND: ContextVar[bool] = ContextVar("display_parser_kind", default=False) 

10 

11 

12@contextmanager 

13def display_context(display_parser_kind: bool): 

14 """AI: Temporarily set whether node display uses parser kind instead of semantic kind.""" 

15 token = DISPLAY_PARSER_KIND.set(display_parser_kind) 

16 try: 

17 yield 

18 finally: 

19 DISPLAY_PARSER_KIND.reset(token) 

20 

21 

22def replace_dollar(text: str) -> str: 

23 """Replace dollar-sign placeholders in the given text with their corresponding match symbols. 

24 

25 Two literal dollar-sign characters (`$$`) are replaced with MATCH_ALL; a single literal dollar-sign 

26 character (`$`) is replaced with MATCH_ONE. 

27 """ 

28 return text.replace("$$", MATCH_ALL).replace("$", MATCH_ONE) 

29 

30 

31def use_dollar(text: str) -> str: 

32 """Replace match symbols in the given text with their corresponding dollar-sign placeholders. 

33 

34 MATCH_ALL is replaced with two literal dollar-sign characters (`$$`); MATCH_ONE is replaced with a 

35 single literal dollar-sign character (`$`). 

36 """ 

37 return text.replace(MATCH_ALL, "$$").replace(MATCH_ONE, "$") 

38 

39 

40def detect_placeholder(signature: str, original_node_type: str) -> tuple[bool, str, str]: 

41 """Detect if the given signature represents a placeholder symbol. 

42 

43 Returns: 

44 (is_placeholder, coerced_node_type, placeholder_name_or_signature) 

45 

46 """ 

47 if not signature: 

48 return False, original_node_type, "" 

49 if signature.startswith((MATCH_ALL, "$$")) and " " not in signature and "(" not in signature: 

50 # legacy compatibility 

51 return True, MATCH_ALL, signature 

52 if signature.startswith((MATCH_ONE, "$")) and " " not in signature and "(" not in signature: 

53 return True, MATCH_ONE, signature 

54 return False, original_node_type, "-" 

55 

56 

57# duplicate of ast node process 

58def traverse(node): 

59 """AI: Yield node and all its descendants in breadth-first order.""" 

60 todo = deque([node]) 

61 while todo: 

62 node = todo.popleft() 

63 if hasattr(node, "children"): 

64 todo.extend(node.children) 

65 yield node 

66 

67 

68def process_node(node, action) -> None: 

69 """AI: Recursively apply action to node and all its descendants.""" 

70 action(node) 

71 if node.children: 

72 for child in node.children: 

73 process_node(child, action) 

74 

75 

76def preceding_sibling(node): 

77 """AI: Return the sibling immediately before node in its parent's children, or None.""" 

78 parent = node.parent 

79 if not parent: 

80 return None 

81 siblings = parent.children 

82 preceding_index = siblings.index(node) - 1 

83 return siblings[preceding_index] if preceding_index >= 0 else None 

84 

85 

86def next_sibling(self): 

87 """AI: Return the sibling immediately after self in its parent's children, or None.""" 

88 parent = self.parent 

89 if not parent: 

90 return None 

91 siblings = parent.children 

92 next_index = siblings.index(self) + 1 

93 return siblings[next_index] if next_index < len(siblings) else None 

94 

95 

96def match_props(mine, other, irrelevant_props) -> bool: 

97 """AI: Return True if mine and other agree on all properties except the irrelevant ones.""" 

98 all_keys = (mine.keys() | other.keys()) - irrelevant_props 

99 return all(mine.get(n) == other.get(n) for n in all_keys) 

100 

101 

102def match_children(mine, other, irrelevant_kinds) -> bool: 

103 """AI: Return True if every child in other matches the corresponding child in mine (or has an irrelevant kind).""" 

104 if mine is None or other is None: 

105 return mine == other 

106 return all((i < len(mine) and mine[i] == child) or child.parser_kind in irrelevant_kinds for i, child in enumerate(other)) 

107 

108 

109def format_node(node) -> str: 

110 """AI: Return a human-readable, indented display string for a single AST node.""" 

111 raw_lines = node.signature.splitlines() 

112 properties_text = "" if not node.show_props else node.properties 

113 prefix = " " if len(raw_lines) < 2 else f"\n {node.indent}" 

114 formatted_lines = [f"{prefix}|{line}|" for line in raw_lines] 

115 semantic_name = node.semantic_kind.value 

116 kind = node.parser_kind if DISPLAY_PARSER_KIND.get() or semantic_name == "node" else semantic_name 

117 return ( 

118 f"{node.indent}({kind}, {node.name}, " 

119 f"{node.filename}[{node.offset}:{node.offset + node.length}])" 

120 f"{properties_text}:{''.join(formatted_lines)}\n" 

121 )