StrictDoc Documentation
strictdoc/backend/sdoc_source_code/tree_sitter_helpers.py
Source file coverage
Path:
strictdoc/backend/sdoc_source_code/tree_sitter_helpers.py
Lines:
47
Non-empty lines:
38
Non-empty lines covered with requirements:
38 / 38 (100.0%)
Functions:
3
Functions covered by requirements:
3 / 3 (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
            break
24
 
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 raise_on_error and child_.type == "ERROR":
38
            raise LookupError("stop search on error node")
39
    return None
40
 
41
 
42
def ts_find_child_nodes_by_type(
43
    node: Node, node_type: str
44
) -> Generator[Node, None, None]:
45
    for child_ in node.children:
46
        if child_.type == node_type:
47
            yield child_