Coverage for parsers / typescript.py: 92%
36 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-08 15:04 -0800
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-08 15:04 -0800
1"""TypeScript tree-sitter parser and function collection."""
3from __future__ import annotations
5import tree_sitter_typescript as tstypescript
6from tree_sitter import Language
8from parsers.common import parse_with_language
9from parsers.shared import create_collect_functions
11TS_LANGUAGE = Language(tstypescript.language_typescript())
12TSX_LANGUAGE = Language(tstypescript.language_tsx())
15def parse(code: str, tsx: bool = False):
16 """Parse TypeScript source code and return the tree root node."""
17 lang = TSX_LANGUAGE if tsx else TS_LANGUAGE
18 return parse_with_language(code, lang)
21def _collect_functions_recursive(node, acc: list) -> None:
22 func_types = {
23 "function_declaration",
24 "function_expression",
25 "method_definition",
26 "generator_function_declaration",
27 }
28 if node.type in func_types:
29 acc.append(node)
30 elif node.type == "arrow_function":
31 if node.parent and node.parent.type == "variable_declarator":
32 acc.append(node)
33 for child in node.children:
34 _collect_functions_recursive(child, acc)
37collect_functions = create_collect_functions(_collect_functions_recursive)
40def func_name(node) -> str:
41 """Extract function name from a function node."""
42 if node.type == "arrow_function":
43 if node.parent and node.parent.type == "variable_declarator":
44 for child in node.parent.children:
45 if child.type == "identifier":
46 return child.text.decode()
47 return "<anonymous>"
48 if node.type == "method_definition":
49 for child in node.children:
50 if child.type == "property_identifier":
51 return child.text.decode()
52 return "<anonymous>"
53 for child in node.children:
54 if child.type == "identifier":
55 return child.text.decode()
56 return "<anonymous>"