ts_parser.py¶
clew/guard/ts_parser.py
Tree-sitter based function detection and doxygen block extraction.
_append_declaration
None clew.guard.ts_parser._append_declaration(Node node, LanguageSpec spec, set[str] exclude, str comment_start_pattern, list[Function] functions, str|None enclosing_class)
Record a documented C/C++ declaration as a Function (2.0.0, PG2).
Called by _collect_functions
Calls _extract_function_name, _extract_signature, _find_preceding_doxygen, _qualified_enclosing
Source · 29 lines
def _append_declaration(
node: Node,
spec: LanguageSpec,
exclude: set[str],
comment_start_pattern: str,
functions: list[Function],
enclosing_class: str | None,
) -> None:
name = _extract_function_name(node, spec)
doxygen = _find_preceding_doxygen(node, spec, comment_start_pattern)
## A `@file` BLOCK DOCUMENTS THE FILE: the first prototype after a header's file block would
## otherwise claim it (found by the undocumented-declaration test).
if name is None or name in exclude or doxygen is None or "file" in doxygen.tags:
return
functions.append(
Function(
name=name,
def_line=node.start_point[0],
body_end=node.end_point[0],
doxygen=doxygen,
enclosing_class=enclosing_class or _qualified_enclosing(node),
signature=_extract_signature(node),
is_declaration=True,
)
)
# A TypeScript return annotation that means "no value": `void`, `never`, `undefined`,
# and the same wrapped in `Promise<...>`.Activity · 5 steps
Requirements
Flows
_bound_function
Node | None clew.guard.ts_parser._bound_function(Node node)
Version 1.1 sees through forwardRef / memo , so a wrapped React component is a function: without it a component declared that way had no definition and every that rendered it resolved to nothing.
Source · 15 lines
def _bound_function(node: Node) -> Node | None:
if node.type not in _JS_BINDINGS:
return None
## A DESTRUCTURING PATTERN IS NOT A NAME: `const {result} = f(() => ...)` binds parts of a
## value, never a function called `{result}`.
name = node.child_by_field_name("name")
if name is None or name.type not in (
"identifier",
"property_identifier",
"private_property_identifier",
):
return None
return _unwrap_component(node.child_by_field_name("value"))
Activity · 6 steps
Requirements
Flows
_collect_c_comment
list[Node] | None clew.guard.ts_parser._collect_c_comment(Node|None prev, LanguageSpec spec)
Collect C-style doxygen comment block preceding a node.
Source · 13 lines
def _collect_c_comment(
prev: Node | None,
spec: LanguageSpec,
) -> list[Node] | None:
comment = _resolve_comment_node(prev, spec)
if comment is None:
return None
block_text = comment.text.decode("utf-8").strip()
if not block_text.startswith("/**") or block_text.startswith("/***"):
return None
return [comment]
Activity · 7 steps
Flows
_collect_functions
None clew.guard.ts_parser._collect_functions(Node node, LanguageSpec spec, set[str] exclude, str comment_start_pattern, list[Function] functions, str|None enclosing_class=None)
Version 2: the payload carries typed class members ( variables ).
Called by parse_functions_ts
Calls _append_declaration, _declared_function, _enclosing_class_for, _extract_function_name, _extract_signature, _find_preceding_doxygen, _function_carrier, _is_rust_test_item, _js_returns_void, _produced_class, _qualified_enclosing, _resolve_function_node
Source · 51 lines
def _collect_functions(
node: Node,
spec: LanguageSpec,
exclude: set[str],
comment_start_pattern: str,
functions: list[Function],
enclosing_class: str | None = None,
) -> None:
for child in node.children:
if spec.doc_style == "rust" and _is_rust_test_item(child):
continue
new_enclosing = _enclosing_class_for(child, enclosing_class)
if spec.doc_style == "c" and _declared_function(child) is not None:
_append_declaration(
child, spec, exclude, comment_start_pattern, functions, new_enclosing
)
continue
func_node = _resolve_function_node(child, spec)
if func_node:
name = _extract_function_name(func_node, spec)
if name is None or name in exclude:
continue
body_node = _function_carrier(func_node).child_by_field_name("body")
if body_node is None:
continue
doxygen = _find_preceding_doxygen(func_node, spec, comment_start_pattern)
resolved_enclosing = new_enclosing or _qualified_enclosing(func_node)
functions.append(
Function(
name=name,
def_line=func_node.start_point[0],
body_end=func_node.end_point[0],
doxygen=doxygen,
enclosing_class=resolved_enclosing,
signature=_extract_signature(func_node),
returns_void=_js_returns_void(func_node) if spec.doc_style == "jsdoc" else None,
)
)
## A MIXIN'S MEMBERS ARE CLASS-LEVEL DEFINITIONS (owner's ruling, 1.3.0): the gate
## descends into the class a bound function produces, exactly as the index does.
mixin = _produced_class(func_node) if spec.doc_style == "jsdoc" else None
if mixin is not None:
body = mixin.child_by_field_name("body")
if body is not None:
_collect_functions(body, spec, exclude, comment_start_pattern, functions, name)
else:
_collect_functions(
child, spec, exclude, comment_start_pattern, functions, new_enclosing
)
Activity · 25 steps
Requirements
Flows
_collect_python_comments
list[Node] | None clew.guard.ts_parser._collect_python_comments(Node|None prev, LanguageSpec spec)
Collect Python-style doxygen comment lines preceding a node.
Source · 21 lines
def _collect_python_comments(
prev: Node | None,
spec: LanguageSpec,
) -> list[Node] | None:
lines: list[Node] = []
expected_line: int | None = None
while prev and prev.type in spec.comment_node_types:
if expected_line is not None and prev.end_point[0] != expected_line:
break
lines.insert(0, prev)
expected_line = prev.start_point[0] - 1
prev = prev.prev_named_sibling
if not lines:
return None
block_text = "\n".join(n.text.decode("utf-8") for n in lines)
if _FILE_TAG_RE.search(block_text):
return None
first_text = lines[0].text.decode("utf-8").strip()
return lines if _PY_DOXYGEN_OPEN_RE.match(first_text) else None
Activity · 15 steps
Requirements
Flows
_collect_rust_doc
list[Node] | None clew.guard.ts_parser._collect_rust_doc(Node|None prev)
Collect the rustdoc outer doc comment ending at prev .
Source · 19 lines
def _collect_rust_doc(prev: Node | None) -> list[Node] | None:
if prev is not None and prev.type == "block_comment":
text = (prev.text or b"").decode("utf-8", errors="replace").strip()
return [prev] if _RUST_BLOCK_DOC_RE.match(text) else None
lines: list[Node] = []
expected_line: int | None = None
while prev is not None and prev.type in ("line_comment", "attribute_item"):
if expected_line is not None and _last_row(prev) < expected_line - 1:
break
if prev.type == "line_comment":
text = (prev.text or b"").decode("utf-8", errors="replace").strip()
if not _RUST_LINE_DOC_RE.match(text):
break
lines.insert(0, prev)
expected_line = prev.start_point[0]
prev = prev.prev_named_sibling
return lines or None
Activity · 16 steps
Requirements
Flows
_declared_function
Node | None clew.guard.ts_parser._declared_function(Node node)
The function declarator a C/C++ declaration declares, or None for anything else.
Source · 12 lines
def _declared_function(node: Node) -> Node | None:
if node.type not in ("declaration", "field_declaration"):
return None
declarator = node.child_by_field_name("declarator")
while declarator is not None and declarator.type in _RETURN_WRAPPERS:
declarator = declarator.child_by_field_name("declarator")
if declarator is None or declarator.type != "function_declarator":
return None
inner = declarator.child_by_field_name("declarator")
return declarator if inner is not None and inner.type != "parenthesized_declarator" else None
Activity · 9 steps
Flows
_enclosing_class_for
str | None clew.guard.ts_parser._enclosing_class_for(Node child, str|None parent)
Resolve enclosing class name when entering a class/struct node.
Source · 18 lines
def _enclosing_class_for(child: Node, parent: str | None) -> str | None:
if child.type in (
"class_specifier",
"struct_specifier",
"class_definition",
"trait_item",
"class_declaration",
"abstract_class_declaration",
"class",
):
name_node = child.child_by_field_name("name")
if name_node and name_node.text:
return name_node.text.decode("utf-8")
if child.type == "impl_item":
return _rust_impl_self_type(child) or parent
return parent
Activity · 7 steps
Flows
_extract_function_name
str | None clew.guard.ts_parser._extract_function_name(Node node, LanguageSpec spec)
Extract function name from an AST function node.
Called by _append_declaration, _collect_functions, _function_record
Calls _name_from_declarator
Source · 8 lines
def _extract_function_name(node: Node, spec: LanguageSpec) -> str | None:
name_node = node.child_by_field_name("name")
if name_node:
return name_node.text.decode("utf-8")
declarator = node.child_by_field_name("declarator")
return _name_from_declarator(declarator) if declarator else None
Activity · 5 steps
Flows
_extract_signature
str clew.guard.ts_parser._extract_signature(Node node)
Extract a normalized parameter-list signature from a function node.
Called by _append_declaration, _collect_functions, _function_record
Calls _function_carrier
Source · 12 lines
def _extract_signature(node: Node) -> str:
node = _function_carrier(node)
params = node.child_by_field_name("parameters")
declarator = node.child_by_field_name("declarator")
while params is None and declarator is not None:
params = declarator.child_by_field_name("parameters")
declarator = declarator.child_by_field_name("declarator")
if params is None or params.text is None:
return ""
return re.sub(r"\s+", " ", params.text.decode("utf-8")).strip()
Activity · 9 steps
Requirements
Flows
_find_preceding_doxygen
DoxygenBlock | None clew.guard.ts_parser._find_preceding_doxygen(Node func_node, LanguageSpec spec, str comment_start_pattern)
Find the doxygen comment block preceding a function node.
Called by _append_declaration, _collect_functions, _doc_raw
Calls _collect_c_comment, _collect_python_comments, _collect_rust_doc, _find_python_docstring_block, _last_row, _preceding_node, _skip_rust_attributes, apply_autobrief, parse_doxygen_tags
Source · 56 lines
def _find_preceding_doxygen(
func_node: Node,
spec: LanguageSpec,
comment_start_pattern: str,
) -> DoxygenBlock | None:
target = func_node
if func_node.parent and func_node.parent.type in (
"decorated_definition",
"template_declaration",
"linkage_specification",
):
target = func_node.parent
if spec.doc_style == "jsdoc":
while target.parent is not None and target.parent.type in _JS_DOC_WRAPPERS:
target = target.parent
prev = _preceding_node(target)
is_rust = spec.doc_style == "rust"
is_python = not is_rust and "##" in comment_start_pattern
if is_rust:
comment_lines = _collect_rust_doc(_skip_rust_attributes(prev))
elif is_python:
comment_lines = _collect_python_comments(prev, spec)
else:
comment_lines = _collect_c_comment(prev, spec)
if not comment_lines:
if is_python:
return _find_python_docstring_block(func_node)
return None
# Build raw as the contiguous file substring spanning the block so that
# blank lines between comment nodes are preserved. This keeps
# raw.splitlines() aligned 1-1 with file line numbers between
# start_line and end_line, which the staleness check relies on.
start_byte = comment_lines[0].start_byte
end_byte = comment_lines[-1].end_byte
root = func_node
while root.parent is not None:
root = root.parent
source = root.text or b""
raw = source[start_byte:end_byte].decode("utf-8", errors="replace")
tags = parse_doxygen_tags(raw)
if is_rust or spec.doc_style == "jsdoc":
apply_autobrief(raw, tags)
return DoxygenBlock(
start_line=comment_lines[0].start_point[0],
end_line=_last_row(comment_lines[-1]),
tags=tags,
raw=raw,
)
# An outer doc comment: `///` but not `////` (rustdoc reads four or more slashes as a plain
# comment), or `/**` but not `/***`. Inner docs (`//!`, `/*!`) document the enclosing module,
# never the next item, so they are never attributed to a function.Activity · 30 steps
Requirements
Flows
_find_python_docstring_block
DoxygenBlock | None clew.guard.ts_parser._find_python_docstring_block(Node func_node)
Find a docstring inside a Python function body and parse doxygen tags.
Called by _find_preceding_doxygen
Calls _find_python_docstring_node, _strip_docstring_quotes, apply_autobrief, parse_doxygen_tags
Source · 18 lines
def _find_python_docstring_block(func_node: Node) -> DoxygenBlock | None:
string_node = _find_python_docstring_node(func_node)
if string_node is None or not string_node.text:
return None
raw = string_node.text.decode("utf-8", errors="replace")
body = _strip_docstring_quotes(raw)
if not body.strip():
return None
tags = parse_doxygen_tags(body)
apply_autobrief(body, tags)
return DoxygenBlock(
start_line=string_node.start_point[0],
end_line=string_node.end_point[0],
tags=tags,
raw=raw,
)
Activity · 10 steps
Requirements
Flows
_function_carrier
Node clew.guard.ts_parser._function_carrier(Node func_node)
The node that carries a function's body and parameters .
Called by _collect_functions, _extract_signature, _function_record, _js_returns_void, _produced_class, _walk
Calls _bound_function
Source · 4 lines
def _function_carrier(func_node: Node) -> Node:
return _bound_function(func_node) or func_node
Activity · 1 steps
Flows
_is_rust_test_item
bool clew.guard.ts_parser._is_rust_test_item(Node node)
Whether a Rust item is test code: a test function or the #[cfg(test)] module.
Source · 7 lines
def _is_rust_test_item(node: Node) -> bool:
return any(_RUST_TEST_ATTR_RE.match(a) for a in _rust_attributes(node))
# Body nodes whose first statement has no previous sibling. A doxygen block written
# above that first statement is parsed as a child of the *enclosing* declaration,
# positioned before the body, so it must be reached through the body node.Activity · 1 steps
Requirements
Flows
_js_returns_void
bool clew.guard.ts_parser._js_returns_void(Node func_node)
Whether a JS/TS function returns no value, as far as its annotation says.
Source · 7 lines
def _js_returns_void(func_node: Node) -> bool:
annotation = _function_carrier(func_node).child_by_field_name("return_type")
if annotation is None or annotation.text is None:
return True
return bool(_TS_VOID_RETURN_RE.match(annotation.text.decode("utf-8", errors="replace")))
Activity · 4 steps
Requirements
Flows
_last_row
int clew.guard.ts_parser._last_row(Node node)
The last row a node occupies.
Source · 5 lines
def _last_row(node: Node) -> int:
row, column = node.end_point
return row - 1 if column == 0 and row > node.start_point[0] else row
Activity · 2 steps
Flows
_name_from_declarator
str | None clew.guard.ts_parser._name_from_declarator(Node declarator)
Extract the identifier from a C/C++ function_declarator node.
Source · 19 lines
def _name_from_declarator(declarator: Node) -> str | None:
leaf_types = ("identifier", "field_identifier", "destructor_name")
if declarator.type in leaf_types:
return declarator.text.decode("utf-8") if declarator.text else None
recurse_types = (
"identifier",
"function_declarator",
"qualified_identifier",
"field_identifier",
"destructor_name",
)
match = next((c for c in declarator.children if c.type in recurse_types), None)
return _name_from_declarator(match) if match is not None else None
# A doxygen block opens with exactly two hashes. Three or more is a section-header
# convention ("### Setup ###") and must not be read as documentation — a bare
# startswith("##") accepted those, producing an empty-tag block that reported as
# "missing @brief" instead of "no doxygen comment".Activity · 6 steps
Flows
_preceding_node
Node | None clew.guard.ts_parser._preceding_node(Node target)
Find the node preceding a definition, stepping out of an enclosing body.
Source · 10 lines
def _preceding_node(target: Node) -> Node | None:
prev = target.prev_named_sibling
if prev is not None:
return prev
parent = target.parent
if parent is not None and parent.type in _BODY_NODE_TYPES:
return parent.prev_named_sibling
return None
Activity · 7 steps
Requirements
Flows
_produced_class
Node | None clew.guard.ts_parser._produced_class(Node func)
The mixin class a bound function produces, or None.
Source · 18 lines
def _produced_class(func: Node) -> Node | None:
"""@brief The class a mixin function returns. @return The class node or None."""
body = _function_carrier(func).child_by_field_name("body")
if body is None:
return None
if body.type == "class":
return body
for stmt in body.named_children if body.type == "statement_block" else ():
value = (
stmt.named_children[0]
if stmt.type == "return_statement" and stmt.named_children
else None
)
if value is not None and value.type == "class":
return value
return None
Activity · 10 steps
Flows
_qualified_enclosing
str | None clew.guard.ts_parser._qualified_enclosing(Node func_node)
Extract enclosing class from a qualified function declarator (Foo::bar).
Source · 10 lines
def _qualified_enclosing(func_node: Node) -> str | None:
declarator = func_node.child_by_field_name("declarator")
while declarator is not None:
if declarator.type == "qualified_identifier":
ns = declarator.child_by_field_name("scope")
if ns and ns.text:
return ns.text.decode("utf-8")
return None
declarator = declarator.child_by_field_name("declarator")
return None1 more lines, not shown
Activity · 9 steps
Flows
_resolve_comment_node
Node | None clew.guard.ts_parser._resolve_comment_node(Node|None prev, LanguageSpec spec)
Resolve a preceding sibling to a comment node.
Source · 14 lines
def _resolve_comment_node(prev: Node | None, spec: LanguageSpec) -> Node | None:
if prev is None:
return None
if prev.type in spec.comment_node_types:
return prev
# Macro calls (e.g. FSM_INITIAL_STATE) can swallow trailing comments as children
last = (
prev.named_children[-1]
if prev.type == "expression_statement" and prev.named_children
else None
)
return last if last is not None and last.type in spec.comment_node_types else None
Activity · 6 steps
Requirements
_resolve_function_node
Node | None clew.guard.ts_parser._resolve_function_node(Node child, LanguageSpec spec)
Resolve a child node to a function_definition, handling wrappers.
Source · 13 lines
def _resolve_function_node(child: Node, spec: LanguageSpec) -> Node | None:
unwrapped = _unwrap_decorated(child)
if unwrapped.type in spec.function_node_types:
return unwrapped
if spec.doc_style == "jsdoc" and _bound_function(child) is not None:
return child
if child.type in ("template_declaration", "linkage_specification"):
for sub in child.children:
if sub.type in spec.function_node_types:
return sub
return None
Activity · 10 steps
Requirements
Flows
_rust_attributes
list[str] clew.guard.ts_parser._rust_attributes(Node node)
The attribute texts written directly above a Rust item, e.g.
Source · 14 lines
def _rust_attributes(node: Node) -> list[str]:
attrs: list[str] = []
prev = node.prev_named_sibling
while prev is not None and prev.type in ("attribute_item", "line_comment", "block_comment"):
if prev.type == "attribute_item":
text = (prev.text or b"").decode("utf-8", errors="replace").strip()
attrs.append(re.sub(r"\s+", "", text.removeprefix("#[").removesuffix("]")))
prev = prev.prev_named_sibling
return attrs
# `#[test]`, `#[tokio::test]`, `#[rstest]`-style harness markers, and `#[cfg(test)]` on the
# inline test module. Inline unit tests are idiomatic Rust, so a source file normally carries
# its own tests, and a path exclude cannot separate them from the code under test.Activity · 8 steps
Flows
_rust_impl_self_type
str | None clew.guard.ts_parser._rust_impl_self_type(Node impl_node)
The self type an impl block is for, without generic arguments: Foo for impl Trait for Foo .
Source · 9 lines
def _rust_impl_self_type(impl_node: Node) -> str | None:
type_node = impl_node.child_by_field_name("type")
if type_node is None:
return None
inner = type_node.child_by_field_name("type") if type_node.type == "generic_type" else None
named = inner or type_node
return named.text.decode("utf-8") if named.text else None
Activity · 6 steps
Flows
_skip_rust_attributes
Node | None clew.guard.ts_parser._skip_rust_attributes(Node|None prev)
Step back over the #[...] attributes between a Rust item and its doc comment.
Source · 6 lines
def _skip_rust_attributes(prev: Node | None) -> Node | None:
while prev is not None and prev.type == "attribute_item":
prev = prev.prev_named_sibling
return prev
Activity · 3 steps
Requirements
Flows
_unwrap_decorated
Node clew.guard.ts_parser._unwrap_decorated(Node node)
Unwrap a decorated_definition to get the inner definition.
Source · 8 lines
def _unwrap_decorated(node: Node) -> Node:
if node.type == "decorated_definition":
for child in node.children:
if child.type in ("function_definition", "class_definition"):
return child
return node
Activity · 5 steps
Flows
parse_functions_ts
list[Function] clew.guard.ts_parser.parse_functions_ts(str content, str lang_name, list[str]|None exclude_names=None, str comment_start_pattern=r"/\*\*(?!\*)")
Parse functions from source content using tree-sitter.
Called by parse_functions
Tested by 22 tests
test_basic_c_function, test_basic_python_function, test_body_end_line, test_cloud_fixture, test_decorated_function, test_doxygen_tags_extracted, test_exclude_names, test_forward_declaration_excluded, test_function_without_doxygen, test_inline_constructor, test_inline_destructor, test_method_not_constructor
Calls _collect_functions, get_language_spec, get_parser_for_language
Source · 24 lines
def parse_functions_ts(
content: str,
lang_name: str,
exclude_names: list[str] | None = None,
comment_start_pattern: str = r"/\*\*(?!\*)",
) -> list[Function]:
parser = get_parser_for_language(lang_name)
if parser is None:
logger.warning("No parser for language %s, skipping", lang_name)
return []
spec = get_language_spec(lang_name)
if spec is None:
return []
exclude = set(exclude_names or [])
tree = parser.parse(content.encode("utf-8"))
functions: list[Function] = []
_collect_functions(tree.root_node, spec, exclude, comment_start_pattern, functions)
return functions