Coverage for parsers/typescript.py: 92%

1"""TypeScript tree-sitter parser and function collection."""

2

3 from __future__ import annotations

4

5 import tree_sitter_typescript as tstypescript

6 from tree_sitter import Language

7

8 from parsers.common import parse_with_language

9 from parsers.shared import create_collect_functions

10

11 TS_LANGUAGE = Language(tstypescript.language_typescript())

12 TSX_LANGUAGE = Language(tstypescript.language_tsx())

13

14

15 def 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)

19

20

21 def _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)

35

36

37 collect_functions = create_collect_functions(_collect_functions_recursive)

38

39

40 def 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>"