Path:
strictdoc/backend/sdoc_source_code/tree_sitter_helpers.py
Lines:
64
Non-empty lines:
52
Non-empty lines covered with requirements:
52 / 52 (100.0%)
Functions:
4
Functions covered by requirements:
4 / 4 (100.0%)
1
"""2
@relation(SDOC-SRS-142, scope=file)3
"""4
5
from typing import Generator, Optional, Tuple, Union
6
7
from tree_sitter import Node, Tree
8
9
10
def traverse_tree(tree: Tree) -> Generator[Node, None, None]:
11
cursor = tree.walk()
12
13
visited_children = False
14
while True:
15
if not visited_children:
16
if cursor.node is not None:
17
yield cursor.node
18
if not cursor.goto_first_child():
19
visited_children = True
20
elif cursor.goto_next_sibling():
21
visited_children = False
22
elif not cursor.goto_parent():
23
break24
25
26
def ts_find_child_node_by_type(
27
node: Node,
28
node_type: Union[str, Tuple[str, ...], str],
29
raise_on_error: bool = False,
30
) -> Optional[Node]:
31
node_types: Tuple[str, ...] = (
32
node_type if isinstance(node_type, tuple) else (node_type,)
33
)34
for child_ in node.children:
35
if child_.type in node_types:
36
return child_
37
elif (
38
raise_on_error39
and child_.type == "ERROR"
40
and not _ts_is_identifier_only_error_node(child_)
41
):42
raise LookupError("stop search on error node")
43
return None
44
45
46
def ts_find_child_nodes_by_type(
47
node: Node, node_type: str
48
) -> Generator[Node, None, None]:
49
for child_ in node.children:
50
if child_.type == node_type:
51
yield child_
52
53
54
def _ts_is_identifier_only_error_node(node: Node) -> bool:
55
"""
56
Check if an ERROR node contains only identifiers.57
58
Tree-sitter creates such a node for "MY_ATTR void foo(void) { }": it59
takes MY_ATTR as the return type and puts "void" into the ERROR node.60
"""61
assert node.type == "ERROR"
62
return node.child_count > 0 and all(
63
child_.type == "identifier" for child_ in node.children
64
)