Coverage for src/renaissance/syntax_tree/ast_finder.py: 69%
45 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: Helpers for finding AST nodes matching a predicate or semantic kind."""
9import re
10from collections.abc import Callable, Iterator, Sequence
12from renaissance.syntax_tree.ast_node import ASTNode
13from renaissance.syntax_tree.node_protocol import NodeProtocol
14from renaissance.syntax_tree.semantic_kind import SemanticKind
15from renaissance.utils.ast_utils import traverse
18class ASTFinder:
19 """AI: Static helpers for finding AST nodes matching a predicate or semantic kind."""
21 KIND_MATCH = re.compile(r"[\W_]+")
23 @staticmethod
24 def find_all(ast_node: ASTNode, function: Callable[[ASTNode], Iterator[ASTNode] | bool]) -> Sequence[ASTNode]:
25 """AI: Return all descendant nodes of ast_node for which function returns a truthy value or child iterator."""
26 return list(ASTFinder.__find_all(ast_node, function))
28 # @staticmethod
29 # def find_kind(ast_node: ASTNode, kind: str | re.Pattern[str]) -> Sequence[ASTNode]:
30 # return list(ASTFinder.__matches_kind(ast_node, kind))
32 @staticmethod
33 def find(ast_node: ASTNode, kind: str | re.Pattern[str]) -> Sequence[ASTNode]:
34 """AI: Return all descendant nodes of ast_node whose kind matches the given kind pattern."""
35 return list(ASTFinder.__matches_kind(ast_node, kind))
37 @staticmethod
38 def matches_kind(ast_node: ASTNode | None, kind: str | re.Pattern[str]) -> bool:
39 """AI: Return whether ast_node's kind matches the given kind pattern."""
40 # compare kind with the ast_node kind only using word characters
41 # get kind of the ast_node with only word characters
42 if ast_node is None:
43 return False
44 ast_kind = ASTFinder.KIND_MATCH.sub("", ast_node.kind).lower()
45 pattern = kind if isinstance(kind, re.Pattern) else re.compile(kind, re.IGNORECASE)
46 return pattern.fullmatch(ast_kind) is not None
48 @staticmethod
49 def __find_all(ast_node: ASTNode, function: Callable[[ASTNode], Iterator[ASTNode] | bool]) -> Iterator[ASTNode]:
50 result = function(ast_node)
51 if isinstance(result, bool) and result:
52 yield ast_node
53 elif isinstance(result, Iterator):
54 yield from result
55 for child in ast_node.children:
56 yield from ASTFinder.__find_all(child, function)
58 @staticmethod
59 def __matches_kind(ast_node: ASTNode, kind: str | re.Pattern[str]) -> Iterator[ASTNode]:
60 pattern = kind if isinstance(kind, re.Pattern) else re.compile(kind, re.IGNORECASE)
61 node_kind = ast_node.kind or ""
62 ast_kind = ASTFinder.KIND_MATCH.sub("", node_kind).lower()
64 if pattern.fullmatch(ast_kind):
65 yield ast_node
66 for child in ast_node.children:
67 # assert isinstance(child, type(ast_node)), f'Expected {type(ast_node)} but got {type(child)}'
68 yield from ASTFinder.__matches_kind(child, pattern)
71def find_nodes(ast_node: NodeProtocol, predicate) -> Sequence[NodeProtocol]:
72 """AI: Return all descendants (and ast_node itself) matching predicate, via a full traversal."""
73 return [node for node in traverse(ast_node) if predicate(node)]
76def matches_node(ast_node: NodeProtocol, predicate) -> bool:
77 """AI: Return True if ast_node itself satisfies predicate."""
78 return predicate(ast_node)
81def find_semantic_kind(ast_node: NodeProtocol, kind: SemanticKind) -> Sequence[NodeProtocol]:
82 """AI: Return all nodes under ast_node whose semantic kind matches the given kind."""
83 return find_nodes(ast_node, lambda node: node.semantic_kind is kind)