Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(cobol): measure each paragraph and section for code health (#4439)

Raghav Chamadiya88527f9bdec8
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 0b33caf6c..5275dfd9b 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -36,7 +36,7 @@ resolution and health markers are all static.
| Tier | Languages | What you get |
|------|-----------|--------------|
| **Full** (14) | Python, TypeScript, JavaScript, Svelte, Vue, Astro, Java, Kotlin, Go, Rust, C++, C#, Scala, Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges and code-health markers |
-| **Good** (11) | C, Swift, PHP, Dart, Object Pascal, COBOL, GDScript, VB.NET, Elixir, F#, Objective-C | Everything above except the full health suite. Dart, Object Pascal and PHP get health markers; C, Swift, F# and Objective-C get the complexity-derived ones; the rest get none yet |
+| **Good** (11) | C, Swift, PHP, Dart, Object Pascal, COBOL, GDScript, VB.NET, Elixir, F#, Objective-C | Everything above except the full health suite. Dart, Object Pascal and PHP get health markers; C, Swift, COBOL, F# and Objective-C get the complexity-derived ones; the rest get none yet |
| **Partial** (2) | Luau / Roblox, Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo and `.luaurc` aware), no health markers. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers, no import edges yet |
| **Lightweight** (6) | Clojure, Haskell, Lean 4, Erlang, HTML, QML | A real file-to-file import graph, no symbol-level claims |
| **Structural** (8) | R, Zig, Julia, Elm, OCaml, Crystal, Nim, D | Git history only: blame, hotspots, co-change. No AST parsing |
@@ -88,6 +88,9 @@ its program and the copybooks it copies; `CALL`, `LINK` and `XCTL` bind to a
unique PROGRAM-ID. JCL (`.jcl`, `.prc`, `.proc`) links each job step to the
program or PROC it runs, which makes that program an entry point, and BMS
mapsets (`.bms`) are linked from the programs that send or receive their maps.
+Health measures each paragraph and section as a function: `IF`, `WHEN` arms,
+`PERFORM UNTIL/VARYING` loops and `AND`/`OR` add to its complexity, and data-only
+copybooks have no functions to flag.
Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
resolved case-insensitively within each sfdx project's namespace; its dead-code
findings are review-only. Apex test coverage from the Salesforce CLI is read as a
@@ -299,7 +302,7 @@ The full list per language, with the mechanics behind each gap, is in
| Scala, Ruby | Extract Method (dataflow dialect) |
| GDScript | Health markers (complexity, performance, dataflow) |
| Object Pascal | A dedicated `uses` resolver |
-| COBOL | Dialect coverage, health markers |
+| COBOL | Dialect coverage, health markers beyond complexity |
| VB.NET, Elixir | Health markers |
| F#, Objective-C | Health markers beyond complexity |
| SQL / dbt | Column-level blast radius |
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index 112d271e9..ca0b348e4 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -18,6 +18,7 @@ Tree-sitter AST walker. Single AST pass per file computes:
> | `perf_walk.py` | Performance-risk pass (`_collect_perf_hits`) |
> | `class_analysis.py` | Class-level LCOM4 / god-class metrics (`_compute_lcom4`) |
> | `languages.py` | Per-language tree-sitter `LanguageNodeMap` registry (extension point) |
+> | `cobol.py` | COBOL paragraphs and sections, whose bodies are the siblings after their header |
>
> The package `__init__` re-exports the dataclasses plus `walk_file` /
> `walk_file_complexity`, so importers use
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cobol.py b/packages/core/src/repowise/core/analysis/health/complexity/cobol.py
new file mode 100644
index 000000000..be7897f20
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cobol.py
@@ -0,0 +1,243 @@
+"""Per-paragraph complexity for COBOL.
+
+The COBOL grammar does not wrap a procedure in a node: a ``paragraph_header``
+or ``section_header`` is a leaf, and its statements are the siblings that
+follow it under ``procedure_division`` (as ``extractors/cobol.py``'s
+``cobol_symbol_end_line`` explains). Control flow is flat the same way:
+``if_header`` ... ``else_header`` ... ``END_IF`` are siblings, so nesting is
+rebuilt from the openers, their scope terminators and the sentence period,
+which closes every open scope.
+
+One row per paragraph, per section with statements of its own (those before
+its first paragraph), and per program with statements before its first
+header. Counting follows ``cyclomatic.py``: a branch, loop or ``WHEN`` arm is
++1 CCN and ``1 + depth`` cognitive; ``ELSE IF`` and an ``AT END`` / ``INVALID
+KEY`` / ``ON SIZE ERROR`` / ``ON EXCEPTION`` / ``ON OVERFLOW`` handler are +1
+CCN and a flat +1 cognitive; ``AND`` / ``OR`` are +1 each; ``EVALUATE`` and
+``SEARCH`` open a level and ``WHEN`` / ``WHEN OTHER`` open another, like a
+switch and its cases. ``GO TO`` and ``ALTER`` are breaks in flow: a flat +1
+cognitive. A handler's statements stay at its statement's depth (the ceiling
+of not scoping them to their ``END-READ``). NLOC counts the non-blank lines of
+the code view (comments and sequence areas blank) from the first statement to
+the last, so a masked ``EXEC`` block counts every line it spans.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.cobol import code_view
+from repowise.core.ingestion.extractors.cobol import normalize_cobol_symbol_name
+
+from .dispatch import _MIN_ARMS, dispatch_share
+from .models import FileComplexity, FunctionComplexity
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+_HEADERS = frozenset({"paragraph_header", "section_header"})
+# Children of the procedure division that are not statements of a body.
+_NOT_STATEMENTS = frozenset({"procedure_using_chaining", "comment"})
+# Scope opener -> the terminator that closes it.
+_CLOSERS = {
+ "END_IF": "if_header",
+ "END_EVALUATE": "evaluate_header",
+ "END_SEARCH": "search_statement",
+ "END_PERFORM": "perform_statement_loop",
+}
+_ARMS = frozenset({"when", "when_other"})
+_HANDLERS = frozenset({"at_end", "invalid_key", "on_size_error", "on_exception", "on_overflow"})
+_JUMPS = frozenset({"goto_statement", "alter_statement"})
+_BOOLEANS = frozenset({"AND", "OR"})
+_WHEN = re.compile(rb"\bWHEN\b", re.IGNORECASE)
+_LITERALS = re.compile(rb"'[^']*'|\"[^\"]*\"")
+
+
+def walk_cobol(root: Node, source: bytes) -> FileComplexity:
+ """Rows for every procedure in every program of the parsed file."""
+ lines = code_view(source).split("\n")
+ functions: list[FunctionComplexity] = []
+ for division in _procedure_divisions(root):
+ for name, header, body in _procedures(division):
+ functions.append(_measure(name, header, body, lines))
+ return FileComplexity(
+ functions=functions, classes=[], file_nloc=sum(1 for line in lines if line.strip())
+ )
+
+
+def _procedure_divisions(root: Node) -> list[Node]:
+ found: list[Node] = []
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ if node.type == "procedure_division":
+ found.append(node)
+ else:
+ stack.extend(reversed(node.children))
+ return found
+
+
+def _procedures(division: Node) -> list[tuple[str, Node, list[Node]]]:
+ """``(name, header, statements)`` per procedure, statements grouped under
+ the header before them. The leading statements belong to the program.
+ """
+ procedures: list[tuple[str, Node, list[Node]]] = []
+ name, header, body = _program_name(division), division, []
+ for child in division.named_children:
+ if child.type in _HEADERS:
+ if body and name:
+ procedures.append((name, header, body))
+ raw = (child.text or b"").decode("utf-8", "replace")
+ name, header, body = normalize_cobol_symbol_name(raw, child.type), child, []
+ elif child.type not in _NOT_STATEMENTS:
+ body.append(child)
+ # A copybook's leading statements have no program to name them; they get no row.
+ if body and name:
+ procedures.append((name, header, body))
+ return procedures
+
+
+def _program_name(division: Node) -> str:
+ program = division.parent
+ if program is None or program.type != "program_definition":
+ return ""
+ ident = next((c for c in program.named_children if c.type == "identification_division"), None)
+ raw = (ident.text or b"").decode("utf-8", "replace") if ident is not None else ""
+ return (
+ normalize_cobol_symbol_name(raw, "program_definition")
+ if "PROGRAM-ID" in raw.upper()
+ else ""
+ )
+
+
+def _measure(name: str, header: Node, body: list[Node], lines: list[str]) -> FunctionComplexity:
+ ccn, cognitive, max_nesting = 1, 0, 0
+ # Open scopes, innermost last: an opener's node type, or "when" for an arm.
+ stack: list[str] = []
+ # A top-level EVALUATE of one value is a dispatch (see ``dispatch.py``).
+ tally: _Dispatch | None = None
+ best = _Dispatch()
+
+ def charge(points: int) -> None:
+ nonlocal ccn
+ ccn += points
+ if tally is not None:
+ tally.points += points
+ tally.arm += points
+
+ def close_dispatch() -> None:
+ nonlocal tally, best
+ if tally is not None:
+ tally.heaviest = max(tally.heaviest, tally.arm)
+ if tally.arms >= _MIN_ARMS and tally.points > best.points:
+ best = tally
+ tally = None
+
+ def open_scope(kind: str, points: int) -> None:
+ nonlocal cognitive, max_nesting
+ charge(points)
+ cognitive += 1 + len(stack)
+ stack.append(kind)
+ max_nesting = max(max_nesting, len(stack))
+
+ for node in body:
+ kind = node.type
+ if kind == "period":
+ stack.clear()
+ close_dispatch()
+ elif kind in _CLOSERS:
+ opener = _CLOSERS[kind]
+ if opener in stack:
+ del stack[len(stack) - 1 - stack[::-1].index(opener) :]
+ if not stack:
+ close_dispatch()
+ elif kind in _ARMS:
+ if stack and stack[-1] == "when":
+ stack.pop()
+ # Stacked ``WHEN a WHEN b`` parse as one arm; each selection is a point.
+ points = _selections(node) if kind == "when" else 1
+ open_scope("when", points)
+ if tally is not None and len(stack) == 2:
+ # The arm's own points are the dispatch's, not its body's.
+ tally.arms += 1
+ tally.heaviest = max(tally.heaviest, tally.arm - points)
+ tally.arm = 0
+ elif kind in ("if_header", "search_statement"):
+ open_scope(kind, 1)
+ elif kind == "perform_statement_loop":
+ open_scope(kind, 1 if _has_option(node) else 0)
+ elif kind == "evaluate_header":
+ if not stack and _tests_one_value(node):
+ tally = _Dispatch()
+ open_scope(kind, 0)
+ elif kind == "perform_statement_call_proc" and _has_option(node):
+ # An out-of-line loop: its body is another paragraph.
+ charge(1)
+ cognitive += 1 + len(stack)
+ max_nesting = max(max_nesting, len(stack) + 1)
+ elif kind in _HANDLERS or kind == "else_if_header":
+ charge(1)
+ cognitive += 1
+ elif kind in _JUMPS:
+ cognitive += 1
+ operators = _boolean_operators(node)
+ charge(operators)
+ cognitive += operators
+ close_dispatch()
+
+ first = body[0].start_point[0]
+ last = body[-1].end_point[0]
+ return FunctionComplexity(
+ name=name,
+ start_line=header.start_point[0] + 1,
+ end_line=last + 1,
+ ccn=ccn,
+ max_nesting=max_nesting,
+ cognitive=cognitive,
+ nloc=sum(1 for row in range(first, last + 1) if row < len(lines) and lines[row].strip()),
+ dispatch_share=dispatch_share(best.points, ccn),
+ dispatch_arm=best.heaviest,
+ )
+
+
+@dataclass
+class _Dispatch:
+ """A dispatch's arms, its points, the open arm's points and the heaviest arm's."""
+
+ arms: int = 0
+ points: int = 0
+ arm: int = 0
+ heaviest: int = 0
+
+
+def _has_option(perform: Node) -> bool:
+ """``UNTIL`` / ``VARYING`` / ``TIMES``: the PERFORM loops."""
+ return any(c.type == "perform_option" for c in perform.named_children)
+
+
+def _tests_one_value(evaluate: Node) -> bool:
+ """``EVALUATE X``, not ``EVALUATE TRUE`` (an IF chain) or ``EVALUATE X ALSO Y``."""
+ subjects = [c for c in evaluate.named_children if c.type == "evaluate_subject"]
+ return len(subjects) == 1 and all(
+ c.type not in ("TRUE", "FALSE") for c in subjects[0].named_children
+ )
+
+
+def _selections(when: Node) -> int:
+ """The ``WHEN`` keywords in an arm, string literals aside."""
+ text = _LITERALS.sub(b"", when.text or b"")
+ return max(1, len(_WHEN.findall(text)))
+
+
+def _boolean_operators(node: Node) -> int:
+ count = 0
+ stack = [node]
+ while stack:
+ current = stack.pop()
+ if current.type in _BOOLEANS:
+ count += 1
+ else:
+ stack.extend(current.children)
+ return count
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 954fb2438..1df4d055d 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -1445,6 +1445,21 @@ _PHP = LanguageNodeMap(
)
+# COBOL procedures are header leaves with sibling bodies, so ``cobol.py`` walks
+# them; this map only marks the language as walked.
+_COBOL = LanguageNodeMap(
+ function_kinds=frozenset(),
+ lambda_kinds=frozenset(),
+ branch_kinds=frozenset(),
+ loop_kinds=frozenset(),
+ try_kinds=frozenset(),
+ catch_kinds=frozenset(),
+ switch_kinds=frozenset(),
+ case_kinds=frozenset(),
+ boolean_operator_kinds=frozenset(),
+)
+
+
LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"python": _PY,
"typescript": _TS,
@@ -1478,6 +1493,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"objectivec": _OBJC,
"php": _PHP,
"swift": _SWIFT,
+ "cobol": _COBOL,
}
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 950b232f1..e8e15aaff 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -57,6 +57,7 @@ from .ast_utils import (
_parameter_list,
)
from .class_analysis import _collect_classes
+from .cobol import walk_cobol
from .cyclomatic import _walk_function_body
from .deprecation import is_deprecated
from .dispatch import dispatch_points, dispatch_share
@@ -165,6 +166,9 @@ def walk_file(
log.debug("complexity_walker_parse_failed", path=abs_path, error=str(exc))
return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))
+ if language == "cobol":
+ return walk_cobol(tree.root_node, source)
+
functions: list[FunctionComplexity] = []
fc_by_node_id: dict[int, FunctionComplexity] = {}
# Dialect first: it is a dict hit that rules out most languages before the
diff --git a/tests/unit/health/test_cobol_complexity.py b/tests/unit/health/test_cobol_complexity.py
new file mode 100644
index 000000000..8d0cafb52
--- /dev/null
+++ b/tests/unit/health/test_cobol_complexity.py
@@ -0,0 +1,190 @@
+"""COBOL paragraph complexity: bodies are the siblings after a header, and so is control flow."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.complexity.languages import has_health_dialect
+
+grammar_pack = pytest.importorskip("tree_sitter_language_pack")
+try:
+ grammar_pack.get_language("cobol")
+except Exception as exc: # pragma: no cover - depends on first-use grammar cache/network
+ pytest.skip(f"COBOL grammar unavailable: {exc}", allow_module_level=True)
+
+
+def _program(*procedure: str) -> bytes:
+ lines = [
+ " IDENTIFICATION DIVISION.",
+ " PROGRAM-ID. DEMO.",
+ " DATA DIVISION.",
+ " WORKING-STORAGE SECTION.",
+ " 01 WS-A PIC 9.",
+ " PROCEDURE DIVISION.",
+ *procedure,
+ ]
+ return ("\n".join(lines) + "\n").encode()
+
+
+def _rows(source: bytes, path: str = "DEMO.cbl") -> dict[str, tuple[int, ...]]:
+ fcx = walk_file(path, "cobol", source)
+ return {
+ fc.name: (fc.start_line, fc.end_line, fc.ccn, fc.max_nesting, fc.cognitive, fc.nloc)
+ for fc in fcx.functions
+ }
+
+
+def test_cobol_is_a_language_health_walks() -> None:
+ assert has_health_dialect("cobol")
+
+
+def test_statements_group_under_the_header_before_them() -> None:
+ rows = _rows(
+ _program(
+ " PERFORM P1.",
+ " MAIN SECTION.",
+ " DISPLAY 'X'.",
+ " P1.",
+ " * a comment line",
+ " MOVE 1 TO WS-A",
+ " MOVE 2 TO WS-A.",
+ " P2.",
+ " GOBACK.",
+ )
+ )
+ # name: (start, end, ccn, nesting, cognitive, nloc). A section's row holds
+ # only its own statements; the program's holds those before any header.
+ assert rows == {
+ "DEMO": (6, 7, 1, 0, 0, 1),
+ "MAIN": (8, 9, 1, 0, 0, 1),
+ "P1": (10, 13, 1, 0, 0, 2),
+ "P2": (14, 15, 1, 0, 0, 1),
+ }
+
+
+def test_branches_loops_and_conditions_count_like_other_languages() -> None:
+ rows = _rows(
+ _program(
+ " P1.",
+ " PERFORM UNTIL WS-A > 5 OR WS-A = 0",
+ " IF WS-A = 1 AND WS-A < 3",
+ " ADD 1 TO WS-A",
+ " ELSE",
+ " SUBTRACT 1 FROM WS-A",
+ " END-IF",
+ " END-PERFORM",
+ " PERFORM P2 VARYING WS-A FROM 1 BY 1 UNTIL WS-A > 3",
+ " PERFORM P2 THRU P2",
+ " IF WS-A = 1 DISPLAY 'Y'.",
+ " P2.",
+ " GO TO P1.",
+ )
+ )
+ # Loop + OR, IF + AND, the out-of-line VARYING loop, the last IF; THRU is a call.
+ assert rows["P1"][2:5] == (7, 2, 7)
+ # GO TO is a break in flow: cognitive only.
+ assert rows["P2"][2:5] == (1, 0, 1)
+
+
+def test_evaluate_arms_nest_like_switch_cases_and_a_period_closes_every_scope() -> None:
+ rows = _rows(
+ _program(
+ " P1.",
+ " EVALUATE WS-A",
+ " WHEN 1",
+ " IF WS-A = 1",
+ " DISPLAY 'A'",
+ " END-IF",
+ " WHEN 2",
+ " DISPLAY 'B'",
+ " WHEN OTHER",
+ " IF WS-A = 3 DISPLAY 'C'.",
+ " IF WS-A = 4",
+ " DISPLAY 'D'",
+ " END-IF.",
+ )
+ )
+ # Cognitive: EVALUATE (1), three arms at depth 1 (2 each), two IFs in arms (3 each),
+ # then the IF after the period starts again at depth 0 (1).
+ assert rows["P1"][2:5] == (7, 3, 14)
+
+
+def test_a_dispatch_on_one_value_is_judged_outside_its_arms() -> None:
+ fn = walk_file(
+ "DEMO.cbl",
+ "cobol",
+ _program(
+ " P1.",
+ " EVALUATE WS-A",
+ " WHEN 1 DISPLAY 'A'",
+ " WHEN 2 DISPLAY 'B'",
+ " WHEN OTHER",
+ " IF WS-A = 3 DISPLAY 'C' END-IF",
+ " END-EVALUATE.",
+ ),
+ ).functions[0]
+ assert (fn.ccn, fn.dispatch_share, fn.dispatch_arm) == (5, 1.0, 1)
+ # EVALUATE TRUE is an IF chain, not a dispatch on a value.
+ chain = walk_file(
+ "DEMO.cbl",
+ "cobol",
+ _program(
+ " P1.",
+ " EVALUATE TRUE",
+ " WHEN WS-A = 1 DISPLAY 'A'",
+ " WHEN WS-A = 2 DISPLAY 'B'",
+ " WHEN OTHER DISPLAY 'C'",
+ " END-EVALUATE.",
+ ),
+ ).functions[0]
+ assert chain.dispatch_share == 0.0
+
+
+def test_handlers_search_arms_and_alter_count() -> None:
+ rows = _rows(
+ _program(
+ " P1.",
+ " READ F1 AT END MOVE 1 TO WS-A",
+ " NOT AT END MOVE 2 TO WS-A",
+ " END-READ",
+ " SEARCH WS-T",
+ " AT END DISPLAY 'NONE'",
+ " WHEN WS-A = 1 DISPLAY 'ONE'",
+ " END-SEARCH",
+ " ALTER P2 TO PROCEED TO P1.",
+ )
+ )
+ # AT END twice (NOT AT END is its other side), SEARCH, one WHEN arm.
+ assert rows["P1"][2:5] == (5, 2, 6)
+
+
+def test_data_only_copybook_has_no_procedures() -> None:
+ copybook = b"\n\n 01 CUSTOMER-RECORD.\n 05 CUST-ID PIC 9(9).\n"
+ assert walk_file("CUSTREC.cpy", "cobol", copybook).functions == []
+
+
+def test_procedure_copybook_paragraphs_are_measured() -> None:
+ copybook = (
+ b"\n\n EDIT-YEAR.\n IF WS-A = 0\n MOVE 1 TO WS-A\n"
+ b" END-IF.\n EDIT-YEAR-EXIT.\n EXIT.\n"
+ )
+ rows = _rows(copybook, "CSUTLDPY.cpy")
+ assert rows == {"EDIT-YEAR": (3, 6, 2, 1, 1, 3), "EDIT-YEAR-EXIT": (7, 8, 1, 0, 0, 1)}
+
+
+def test_stacked_when_selections_each_count() -> None:
+ rows = _rows(
+ _program(
+ " P1.",
+ " EVALUATE WS-A",
+ " WHEN 1 THRU 3",
+ " WHEN 'WHEN'",
+ " DISPLAY 'A'",
+ " WHEN OTHER",
+ " DISPLAY 'B'",
+ " END-EVALUATE.",
+ )
+ )
+ # Two stacked selections (the literal 'WHEN' is not one) and WHEN OTHER.
+ assert rows["P1"][2] == 4