Coverage for metrics/lloc/go.py: 100%

1"""LLOC (Logical Lines of Code) for Go."""

2

3 from __future__ import annotations

4

5 _GO_LLOC_TYPES = {

6 # Simple statements

7 "expression_statement", "send_statement",

8 "inc_statement", "dec_statement",

9 "assignment_statement", "short_var_declaration",

10 "return_statement", "go_statement", "defer_statement",

11 "break_statement", "continue_statement", "goto_statement",

12 "fallthrough_statement", "labeled_statement", "empty_statement",

13 # Declarations

14 "function_declaration", "method_declaration",

15 "var_declaration", "const_declaration", "type_declaration",

16 "import_declaration",

17 # Compound statement headers

18 "if_statement",

19 "for_statement",

20 "expression_switch_statement", "type_switch_statement",

21 "select_statement",

22 # Case clauses

23 "expression_case", "type_case", "default_case",

24 "communication_case",

25}

26

27

28 def count_lloc(root) -> int:

29 """Count logical lines of code in a Go AST."""

30 count = 0

31 if root.type in _GO_LLOC_TYPES:

32 count += 1

33 if root.type == "if_statement":

34 alt = root.child_by_field_name("alternative")

35 if alt is not None and alt.type == "block":

36 count += 1 # terminal else

37 for child in root.children:

38 count += count_lloc(child)

39 return count