Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(cobol): list paragraphs that jump out of structured flow with GO TO or ALTER (#4462)
Raghav Chamadiyafc836c55cea5
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex 486aebd44..bc02653a2 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -104,8 +104,8 @@ Each marker is a stateless class implementing the `Biomarker` Protocol### The full roster-`biomarkers/registry.py` registers **58 detectors**; counting the three governance-findings written by the additive pass (`governance.py`) there are **61 marker ids**. They+`biomarkers/registry.py` registers **59 detectors**; counting the three governance+findings written by the additive pass (`governance.py`) there are **62 marker ids**. Theydivide by what each is permitted to affect:| Group | Count | Scores into |@@ -114,7 +114,7 @@ divide by what each is permitted to affect:| Performance | 22 | `performance` only || SQL | 3 | `maintainability` only || Governance | 3 | nothing: the finding surfaces, the score is untouched |-| Advisory | 9 | nothing: measured by construction, out of impact-ranked lists unless requested |+| Advisory | 10 | nothing: measured by construction, out of impact-ranked lists unless requested |The authority is `scoring._BIOMARKER_DIMENSIONS`. An unlisted biomarker defaults into`defect`, so every `sql_*` and performance name is listed explicitly: an omission would@@ -166,6 +166,7 @@ the defect weight (§6.1), "maint" the maintainability and "perf" the performanc| `apex_missing_sharing` | Apex | A top-level class with queries or updates and no sharing keyword | Medium; not subclasses, inner or test classes | Advisory || `apex_hardcoded_id` | Apex | A record Id as a string literal | Medium; 18 chars with a valid checksum or 15 on a standard prefix; non-test Apex | Advisory || `apex_see_all_data` | Apex | `@IsTest(SeeAllData=true)` | Low | Advisory |+| `cobol_unstructured_flow` | COBOL | A paragraph or section with `ALTER`, `GO TO ... DEPENDING ON`, or a `GO TO` that is not a forward jump to an `...EXIT` paragraph of its own `PERFORM THRU` range | Low; one finding per paragraph | Advisory || `io_in_loop` | Performance | I/O per loop iteration (N+1), across functions | Medium | perf 1.0 || `string_concat_in_loop` | Performance | `+=` of a provable string in a loop | Low | perf 0.7 || `blocking_sync_in_async` | Performance | A sync blocking call in `async def` | Medium; Python, Rust, C#, Kotlin, Scala | perf 0.7 |diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex c4d9d959d..548862f72 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -141,7 +141,7 @@ survives re-indexing, and a re-detected `resolved` finding reopens.### Detector families-The 58 detectors fall into families whose caps keep any one from dominating a file.+The 59 detectors fall into families whose caps keep any one from dominating a file.Every id with its threshold and weight:[the full roster](../architecture/code-health.md#the-full-roster).@@ -156,6 +156,7 @@ Every id with its threshold and weight:| Test quality | 4 | 0.5 | Oversized or duplicated assertion blocks; two advisory markers || SQL | 4 | none | Complex SQL, `SELECT *`, `UPDATE`/`DELETE` with no `WHERE`, cartesian joins || Apex | 4 | none | SOQL injection, a class with queries and no sharing keyword, hardcoded record Ids, `SeeAllData=true` tests; all advisory |+| COBOL | 1 | none | `ALTER`, `GO TO ... DEPENDING ON`, and `GO TO` out of a paragraph's `PERFORM THRU` range; advisory || Performance | 21 | none | See [PERFORMANCE.md](PERFORMANCE.md) |- Caps are code-health caps; SQL deducts only in maintainability (2.0) and performancediff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex e528867fe..8d89e67b7 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -98,6 +98,11 @@ copybooks have no functions to flag.A level-88 condition name is a child of the data item it tests, with an id suchas `PROG.cbl::WS-RETURN-FLAG::APPL-AOK`, and stays findable by symbol search.These children do not count toward the 500-symbol warning for generated files.+The advisory `cobol_unstructured_flow` marker lists each paragraph with an `ALTER`,+a `GO TO ... DEPENDING ON`, or a `GO TO` that does not jump forward to an `...EXIT`+paragraph of its own `PERFORM THRU` range; it never deducts from a score.+A paragraph whose performer is in another file (a copybook's) is judged by the+target's name alone.Apex dead-code findings are review-only, since the platform also reaches classesby name.diff --git a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py b/packages/core/src/repowise/core/analysis/health/biomarker_labels.pyindex 7ecd37ba6..f65fd51af 100644--- a/packages/core/src/repowise/core/analysis/health/biomarker_labels.py+++ b/packages/core/src/repowise/core/analysis/health/biomarker_labels.py@@ -71,6 +71,7 @@ BIOMARKER_LABELS: dict[str, str] = {"apex_missing_sharing": "Apex class without sharing","apex_hardcoded_id": "Hardcoded record Id","apex_see_all_data": "Test sees all org data",+ "cobol_unstructured_flow": "GO TO or ALTER out of range",}diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.mdindex fe5be90b5..5ae29ac07 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md@@ -11,8 +11,9 @@ class Biomarker(Protocol):## Registered detectors-`registry.py` registers 58 detectors: the 29 code-health markers below, 22-performance markers, 3 SQL maintainability markers and 4 advisory Apex markers. Every id with its threshold+`registry.py` registers 59 detectors: the 29 code-health markers below, 22+performance markers, 3 SQL maintainability markers, 4 advisory Apex markers and+1 advisory COBOL marker. Every id with its thresholdand weight is in[the full roster](../../../../../../../../docs/architecture/code-health.md#the-full-roster).diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/cobol_unstructured_flow.py b/packages/core/src/repowise/core/analysis/health/biomarkers/cobol_unstructured_flow.pynew file mode 100644index 000000000..e8e137dcc--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/cobol_unstructured_flow.py@@ -0,0 +1,63 @@+"""``cobol_unstructured_flow``: a COBOL paragraph or section whose control leaves+structured flow through ``ALTER``, ``GO TO ... DEPENDING ON`` or a ``GO TO``+that is not its range's exit (``health/complexity/cobol.py`` decides each jump).++One finding per procedure, at its first jump. Advisory: no defect corpus labels+it, so it is listed and never deducts.+"""++from __future__ import annotations++from ..complexity.cobol import UNSTRUCTURED_FLOW+from ..complexity.models import PerfHit+from ..models import Severity+from .base import BiomarkerResult, FileContext+++def _reason(name: str, first: str, count: int) -> str:+ upper = first.upper()+ if upper.startswith("ALTER"):+ what = f"{first} rewrites a GO TO target at runtime, so where {name} sends control"+ what += " depends on which paragraph ran before it"+ elif "DEPENDING" in upper:+ what = f"{first} picks {name}'s next paragraph by value; a reader must trace"+ what += " each target by hand"+ elif upper == "GO TO":+ what = f"GO TO with no target in {name} goes wherever an ALTER last pointed it"+ else:+ what = f"{first} leaves {name} outside its PERFORM range; the paragraph's exit"+ what += " depends on control flow a reader must trace by hand"+ more = count - 1+ return what if not more else f"{what} (and {more} more jump{'s' if more > 1 else ''})"+++class CobolUnstructuredFlowDetector:+ name = UNSTRUCTURED_FLOW+ category = "cobol"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ by_procedure: dict[tuple[str | None, int], list[PerfHit]] = {}+ for hit in ctx.perf_hits:+ if hit.kind == self.name:+ by_procedure.setdefault((hit.function, hit.func_start), []).append(hit)+ results: list[BiomarkerResult] = []+ for (function, _), hits in by_procedure.items():+ hits.sort(key=lambda h: h.line)+ first = hits[0]+ results.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=Severity.LOW,+ function_name=function,+ line_start=first.line,+ line_end=hits[-1].line,+ details={+ "count": len(hits),+ "first_line": first.line,+ # The first few statements; ``count`` carries the rest.+ "jumps": [h.detail for h in hits[:5]],+ },+ reason=_reason(function or "the program", first.detail, len(hits)),+ )+ )+ return resultsdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.pyindex c60f795a7..89927d56e 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py@@ -24,6 +24,7 @@ from .brain_method import BrainMethodDetectorfrom .change_entropy import ChangeEntropyDetectorfrom .churn_risk import ChurnRiskDetectorfrom .co_change_scatter import CoChangeScatterDetector+from .cobol_unstructured_flow import CobolUnstructuredFlowDetectorfrom .code_age_volatility import CodeAgeVolatilityDetectorfrom .complex_conditional import ComplexConditionalDetectorfrom .complex_method import ComplexMethodDetector@@ -140,6 +141,8 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [ApexMissingSharingDetector, # type: ignore[list-item]ApexHardcodedIdDetector, # type: ignore[list-item]ApexSeeAllDataDetector, # type: ignore[list-item]+ # COBOL markers (advisory: listed, never scored).+ CobolUnstructuredFlowDetector, # type: ignore[list-item]]diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cobol.py b/packages/core/src/repowise/core/analysis/health/complexity/cobol.pyindex be7897f20..fc8690413 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cobol.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cobol.py@@ -20,11 +20,28 @@ cognitive. A handler's statements stay at its statement's depth (the ceilingof not scoping them to their ``END-READ``). NLOC counts the non-blank lines ofthe code view (comments and sequence areas blank) from the first statement tothe last, so a masked ``EXEC`` block counts every line it spans.++The same pass records each jump that leaves structured flow as a+``cobol_unstructured_flow`` hit on ``FileComplexity.perf_hits``: every+``ALTER``, every ``GO TO ... DEPENDING ON``, a ``GO TO`` with no target (the+one an ``ALTER`` rewrites), and any other ``GO TO`` unless it jumps forward to+an exit of its own range. An exit is a header named ``EXIT`` or ``...-EXIT``.+A range is a ``PERFORM X THRU Y`` in the same procedure division (or a+performed section, which ends at its last paragraph); a procedure from ``X``+through ``Y`` stays silent on a ``GO TO`` to a later exit up to ``Y``, and a+procedure in no range seen in the file stays silent on a ``GO TO`` to any+later exit. A name qualified ``OF``/``IN`` a section resolves in that section;+an unqualified name used in several sections resolves to the one in the+referring procedure's section, else the first after it, else the first.+Ceiling: the second case trusts the name, since its performer (the program+that copies a copybook, or nothing at all) is out of sight; nested ranges are+not told apart, so a jump to an enclosing range's exit stays silent."""from __future__ import annotationsimport re+from bisect import bisect_rightfrom dataclasses import dataclassfrom typing import TYPE_CHECKING@@ -32,11 +49,13 @@ from repowise.core.ingestion.cobol import code_viewfrom repowise.core.ingestion.extractors.cobol import normalize_cobol_symbol_namefrom .dispatch import _MIN_ARMS, dispatch_share-from .models import FileComplexity, FunctionComplexity+from .models import FileComplexity, FunctionComplexity, PerfHitif TYPE_CHECKING:from tree_sitter import Node+UNSTRUCTURED_FLOW = "cobol_unstructured_flow"+_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"})@@ -59,14 +78,152 @@ 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] = []+ hits: list[PerfHit] = []for division in _procedure_divisions(root):+ ranges = _Ranges(division)for name, header, body in _procedures(division):functions.append(_measure(name, header, body, lines))+ hits.extend(_jumps(name, header, body, ranges))return FileComplexity(- functions=functions, classes=[], file_nloc=sum(1 for line in lines if line.strip())+ functions=functions,+ classes=[],+ file_nloc=sum(1 for line in lines if line.strip()),+ perf_hits=hits,)+def _label(node: Node) -> tuple[str, str]:+ """``(name, section)`` of a procedure label; ``section`` is "" unless qualified."""+ word = next((c for c in node.named_children if c.type == "qualified_word"), node)+ parts = [(c.text or b"").decode("utf-8", "replace").upper() for c in word.named_children]+ parts = parts or (node.text or b"").decode("utf-8", "replace").upper().split()[:1]+ return (parts[0], parts[-1] if len(parts) > 1 else "") if parts else ("", "")+++def _is_exit(name: str) -> bool:+ return name == "EXIT" or name.endswith("-EXIT")+++def _performs(division: Node) -> list[Node]:+ """Every ``perform_procedure`` (the ``X [THRU Y]`` of a PERFORM) under *division*."""+ found: list[Node] = []+ stack = [division]+ while stack:+ node = stack.pop()+ if node.type == "perform_procedure":+ found.append(node)+ else:+ stack.extend(node.named_children)+ return found+++class _Ranges:+ """The headers of one procedure division and the PERFORM ranges over them."""++ def __init__(self, division: Node) -> None:+ # Per header: name, kind, the section it is in, and where it starts.+ self.order: list[tuple[str, str, str]] = []+ self.starts: list[int] = []+ self._collect_headers(division)+ self.where: dict[str, list[int]] = {}+ for i, (name, _, _) in enumerate(self.order):+ self.where.setdefault(name, []).append(i)+ # Header index -> the furthest end of a range it sits in.+ self.bound: dict[int, int] = {}+ for perform in _performs(division):+ span = self._span(perform)+ if span is not None:+ start, end = span+ for i in range(start, end + 1):+ self.bound[i] = max(self.bound.get(i, end), end)++ def _collect_headers(self, division: Node) -> None:+ section = ""+ for child in division.named_children:+ if child.type not in _HEADERS:+ continue+ raw = (child.text or b"").decode("utf-8", "replace")+ name = normalize_cobol_symbol_name(raw, child.type)+ if child.type == "section_header":+ section = name+ self.order.append((name, child.type, section))+ self.starts.append(child.start_byte)++ def _span(self, perform: Node) -> tuple[int, int] | None:+ """First and last header a ``perform_procedure`` runs, or None if unresolved."""+ labels = [_label(c) for c in perform.named_children if c.type == "label"]+ if not labels:+ return None+ start = self.find(*labels[0], at=bisect_right(self.starts, perform.start_byte) - 1)+ end = None if start is None else self.find(*labels[-1], at=start)+ if start is None or end is None or end < start:+ return None+ return start, self._last(end)++ def at(self, header: Node) -> int:+ """The header's index; -1 for a program's leading statements."""+ i = bisect_right(self.starts, header.start_byte) - 1+ return i if i >= 0 and self.starts[i] == header.start_byte else -1++ def find(self, name: str, section: str, at: int) -> int | None:+ """The header *name* (qualified by *section*) means when used from header *at*."""+ found = self.where.get(name, [])+ if section:+ found = [i for i in found if self.order[i][2] == section]+ if len(found) < 2:+ return found[0] if found else None+ here = self.order[at][2] if at >= 0 else ""+ same = [i for i in found if self.order[i][2] == here]+ later = [i for i in found if i > at]+ return (same or later or found)[0]++ def _last(self, i: int) -> int:+ """A section runs to the header before the next section."""+ if self.order[i][1] != "section_header":+ return i+ j = i + 1+ while j < len(self.order) and self.order[j][1] != "section_header":+ j += 1+ return j - 1++ def exits_to(self, header: Node, target: tuple[str, str]) -> bool:+ """Whether ``GO TO target`` from *header* jumps forward to an exit of its range."""+ at = self.at(header)+ to = self.find(*target, at=at)+ return (+ to is not None+ and _is_exit(target[0])+ and at < to <= self.bound.get(at, len(self.order) - 1)+ )+++def _jumps(name: str, header: Node, body: list[Node], ranges: _Ranges) -> list[PerfHit]:+ """The procedure's jumps that leave structured flow (see the module doc)."""+ hits: list[PerfHit] = []+ for node in body:+ if node.type not in _JUMPS:+ continue+ text = " ".join((node.text or b"").decode("utf-8", "replace").split())+ if node.type == "goto_statement":+ labels = [_label(c) for c in node.named_children if c.type == "label"]+ if (+ len(labels) == 1+ and "DEPENDING" not in text.upper()+ and ranges.exits_to(header, labels[0])+ ):+ continue+ hits.append(+ PerfHit(+ kind=UNSTRUCTURED_FLOW,+ line=node.start_point[0] + 1,+ function=name,+ detail=text,+ func_start=header.start_point[0] + 1,+ )+ )+ return hits++def _procedure_divisions(root: Node) -> list[Node]:found: list[Node] = []stack = [root]diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex ac39d0966..94b3a9704 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -229,6 +229,8 @@ _BIOMARKER_CATEGORY: dict[str, str] = {"apex_missing_sharing": "apex","apex_hardcoded_id": "apex","apex_see_all_data": "apex",+ # Advisory COBOL marker.+ "cobol_unstructured_flow": "cobol",}@@ -340,6 +342,8 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {"apex_missing_sharing": {ADVISORY_DIMENSION},"apex_hardcoded_id": {ADVISORY_DIMENSION},"apex_see_all_data": {ADVISORY_DIMENSION},+ # Uncalibrated COBOL marker: GO TO and ALTER already add cognitive points.+ "cobol_unstructured_flow": {ADVISORY_DIMENSION},}# Maintainability per-biomarker weight multipliers. Expert-set by definition -@@ -571,6 +575,7 @@ _ADVISORY_HOME: frozenset[str] = frozenset("apex_missing_sharing","apex_hardcoded_id","apex_see_all_data",+ "cobol_unstructured_flow",})diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.pyindex 68f279181..7c1cfe4e7 100644--- a/packages/core/src/repowise/core/analysis/health/suggestions.py+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py@@ -333,6 +333,11 @@ _TEMPLATES: dict[str, str] = {"Create the test's data. Insert the records the test needs (a test data ""factory or @TestSetup) and drop SeeAllData=true."),+ "cobol_unstructured_flow": (+ "Return through the range exit. Replace the jump with a flag the caller "+ "tests, or PERFORM the target paragraph, and set the next step with a "+ "value instead of ALTER."+ ),}diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.tsindex 1aa8bcbb0..942940fcb 100644--- a/packages/ui/src/health/biomarker-glossary.ts+++ b/packages/ui/src/health/biomarker-glossary.ts@@ -22,7 +22,8 @@ export type BiomarkerCategory =| "performance"| "organizational"| "sql"- | "apex";+ | "apex"+ | "cobol";export interface BiomarkerInfo {label: string;@@ -42,6 +43,7 @@ export const CATEGORY_LABEL: Record<BiomarkerCategory, string> = {organizational: "Organizational",sql: "SQL",apex: "Apex",+ cobol: "COBOL",};export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {@@ -63,6 +65,8 @@ export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {sql: 2.0,// Apex markers are advisory: listed, never deducted.apex: 0,+ // The COBOL marker is advisory too.+ cobol: 0,};export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {@@ -432,6 +436,12 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {description:"A test class or method annotated @IsTest(SeeAllData=true): it reads the org's live data, so it can pass in one org and fail in another. Advisory: it never deducts.",},+ cobol_unstructured_flow: {+ label: BIOMARKER_LABELS.cobol_unstructured_flow,+ category: "cobol",+ description:+ "A COBOL paragraph or section with an ALTER, a GO TO ... DEPENDING ON, or a GO TO to anything other than an exit paragraph of the PERFORM THRU range it sits in, so where control goes next has to be traced by hand. GO TO X-EXIT inside its own range is not flagged. Advisory: it never deducts.",+ },};export function biomarkerInfo(name: string): BiomarkerInfo {@@ -476,6 +486,7 @@ export const ADVISORY_HOME_BIOMARKERS: ReadonlySet<string> = new Set(["apex_missing_sharing","apex_hardcoded_id","apex_see_all_data",+ "cobol_unstructured_flow",]);/**diff --git a/packages/ui/src/health/generated/biomarker-labels.ts b/packages/ui/src/health/generated/biomarker-labels.tsindex a16315ca4..3d663f5eb 100644--- a/packages/ui/src/health/generated/biomarker-labels.ts+++ b/packages/ui/src/health/generated/biomarker-labels.ts@@ -65,6 +65,7 @@ export const BIOMARKER_LABELS = {apex_missing_sharing: "Apex class without sharing",apex_hardcoded_id: "Hardcoded record Id",apex_see_all_data: "Test sees all org data",+ cobol_unstructured_flow: "GO TO or ALTER out of range",} as const;/** Renamed ids (old -> current), so rows stored under an old id get the current label. */diff --git a/packages/ui/src/health/plain-language.ts b/packages/ui/src/health/plain-language.tsindex ea864712d..a2fe3fadc 100644--- a/packages/ui/src/health/plain-language.ts+++ b/packages/ui/src/health/plain-language.ts@@ -63,6 +63,10 @@ const BY_CATEGORY: Record<BiomarkerCategory, PlainIssue> = {title: "Apex security or test risk",why: "It can expose records, break in another org, or depend on org data.",},+ cobol: {+ title: "Jump out of structured flow",+ why: "Where control goes next has to be traced by hand.",+ },};const BY_BIOMARKER: Record<string, PlainIssue> = {diff --git a/tests/unit/health/test_cobol_unstructured_flow.py b/tests/unit/health/test_cobol_unstructured_flow.pynew file mode 100644index 000000000..fbc7f56d1--- /dev/null+++ b/tests/unit/health/test_cobol_unstructured_flow.py@@ -0,0 +1,281 @@+"""``cobol_unstructured_flow``: ALTER, GO TO ... DEPENDING ON and GO TO out of a+PERFORM range fire; GO TO to the range's own exit stays silent; advisory."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.biomarkers.base import FileContext+from repowise.core.analysis.health.biomarkers.registry import detect_all+from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.scoring import biomarker_dimension, dimensions_for, score_file++grammar_pack = pytest.importorskip("tree_sitter_language_pack")+try:+ grammar_pack.get_language("cobol")+except (grammar_pack.Error, OSError) as exc: # pragma: no cover - first-use download+ pytest.skip(f"COBOL grammar unavailable: {exc}", allow_module_level=True)++_KIND = "cobol_unstructured_flow"+++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 _hits(source: bytes) -> list[tuple[str | None, str]]:+ fcx = walk_file("DEMO.cbl", "cobol", source)+ return [(h.function, h.detail) for h in fcx.perf_hits if h.kind == _KIND]+++def _findings(source: bytes):+ fcx = walk_file("DEMO.cbl", "cobol", source)+ ctx = FileContext(+ file_path="DEMO.cbl", language="cobol", nloc=20, has_test_file=False,+ module=None, perf_hits=fcx.perf_hits,+ )+ return [r for r in detect_all(ctx) if r.biomarker_type == _KIND]+++def test_go_to_own_range_exit_is_silent() -> None:+ assert _hits(+ _program(+ " PERFORM A THRU A-EXIT.",+ " GOBACK.",+ " A.",+ " IF WS-A = 1",+ " GO TO A-EXIT",+ " END-IF",+ " GO TO A-COMMON-EXIT.",+ " A-COMMON-EXIT.",+ " MOVE 0 TO WS-A.",+ " A-EXIT.",+ " EXIT.",+ )+ ) == []+++def test_go_to_elsewhere_fires() -> None:+ assert _hits(+ _program(+ " PERFORM A THRU A-EXIT.",+ " GOBACK.",+ " A.",+ " GO TO COMMON-RETURN.",+ " A-EXIT.",+ " EXIT.",+ " COMMON-RETURN.",+ " GOBACK.",+ )+ ) == [("A", "GO TO COMMON-RETURN")]+++def test_go_to_an_enclosing_exit_from_a_later_range_fires() -> None:+ # B is performed on its own range and sits after A-EXIT: jumping back to+ # A-EXIT abandons B's PERFORM.+ assert _hits(+ _program(+ " PERFORM A THRU A-EXIT.",+ " GOBACK.",+ " A.",+ " PERFORM B THRU B-EXIT.",+ " A-EXIT.",+ " EXIT.",+ " B.",+ " GO TO A-EXIT.",+ " B-EXIT.",+ " EXIT.",+ )+ ) == [("B", "GO TO A-EXIT")]+++def test_loop_back_to_own_header_fires() -> None:+ assert _hits(+ _program(+ " A-GAIN.",+ " ADD 1 TO WS-A",+ " IF WS-A < 5 GO TO A-GAIN END-IF.",+ )+ ) == [("A-GAIN", "GO TO A-GAIN")]+++def test_alter_and_depending_on_fire() -> None:+ assert _hits(+ _program(+ " A.",+ " ALTER B TO PROCEED TO C",+ " GO TO C D DEPENDING ON WS-A.",+ " B.",+ " GO TO.",+ " C.",+ " EXIT.",+ " D.",+ " EXIT.",+ )+ ) == [+ ("A", "ALTER B TO PROCEED TO C"),+ ("A", "GO TO C D DEPENDING ON WS-A"),+ ("B", "GO TO"),+ ]+++def test_unperformed_paragraph_trusts_the_exit_name() -> None:+ # A copybook's paragraphs are performed from the program that copies it.+ assert _hits(+ _program(+ " EDIT-DAY.",+ " GO TO EDIT-DAY-EXIT.",+ " EDIT-DAY-EXIT.",+ " EXIT.",+ )+ ) == []+++def test_qualified_go_to_and_thru_resolve_in_their_section() -> None:+ assert _hits(+ _program(+ " PERFORM A OF S1 THRU A-EXIT IN S1.",+ " GOBACK.",+ " S1 SECTION.",+ " A.",+ " GO TO A-EXIT OF S1.",+ " A-EXIT.",+ " EXIT.",+ )+ ) == []+++def test_thru_spanning_sections() -> None:+ assert _hits(+ _program(+ " PERFORM S1 THRU S2.",+ " GOBACK.",+ " S1 SECTION.",+ " A.",+ " GO TO S2-EXIT.",+ " S2 SECTION.",+ " B.",+ " MOVE 1 TO WS-A.",+ " S2-EXIT.",+ " EXIT.",+ )+ ) == []+++def test_thru_on_a_continuation_line_and_lowercase_names() -> None:+ assert _hits(+ _program(+ " perform a",+ " thru a-exit.",+ " goback.",+ " a.",+ " go to a-exit.",+ " a-exit.",+ " exit.",+ )+ ) == []+++def test_duplicate_names_resolve_in_the_current_section() -> None:+ # Each section has its own P-EXIT; Q's jump means S2's, which a+ # first-header lookup would place behind it.+ assert _hits(+ _program(+ " PERFORM P THRU P-EXIT OF S1.",+ " PERFORM Q THRU P-EXIT OF S2.",+ " GOBACK.",+ " S1 SECTION.",+ " P.",+ " GO TO P-EXIT.",+ " P-EXIT.",+ " EXIT.",+ " S2 SECTION.",+ " Q.",+ " GO TO P-EXIT.",+ " P-EXIT.",+ " EXIT.",+ )+ ) == []+++def test_go_to_from_the_range_end_to_a_later_exit_fires() -> None:+ assert _hits(+ _program(+ " PERFORM A THRU A-EXIT.",+ " GOBACK.",+ " A.",+ " MOVE 1 TO WS-A.",+ " A-EXIT.",+ " GO TO Z-EXIT.",+ " Z-EXIT.",+ " EXIT.",+ )+ ) == [("A-EXIT", "GO TO Z-EXIT")]+++def test_depending_on_reason_makes_no_claim_about_targets() -> None:+ (finding,) = _findings(+ _program(+ " A.",+ " GO TO B C DEPENDING ON WS-A.",+ " B.",+ " EXIT.",+ " C.",+ " EXIT.",+ )+ )+ assert finding.reason == (+ "GO TO B C DEPENDING ON WS-A picks A's next paragraph by value; "+ "a reader must trace each target by hand"+ )++[email protected]("target", ["CHECKEXIT", "NOEXIT"])+def test_exit_needs_a_hyphen_suffix(target: str) -> None:+ assert _hits(+ _program(+ " PERFORM A THRU " + target + ".",+ " GOBACK.",+ " A.",+ " GO TO " + target + ".",+ " " + target + ".",+ " EXIT.",+ )+ ) == [("A", "GO TO " + target)]+++def test_one_finding_per_procedure_and_advisory() -> None:+ results = _findings(+ _program(+ " A.",+ " IF WS-A = 1 GO TO Z END-IF",+ " GO TO Z.",+ " Z.",+ " GOBACK.",+ )+ )+ assert len(results) == 1+ (finding,) = results+ assert finding.function_name == "A"+ assert finding.details["count"] == 2+ assert finding.details["first_line"] == 8+ assert finding.reason.startswith("GO TO Z leaves A outside its PERFORM range")+ assert dimensions_for(_KIND) == {"advisory"}+ assert biomarker_dimension(_KIND) == "advisory"+ scores, deductions = score_file(results)+ assert set(deductions) == {0.0}+ assert scores["defect"] == scores["maintainability"] == scores["performance"] == 10.0+++def test_jumps_keep_the_cognitive_point() -> None:+ fcx = walk_file("DEMO.cbl", "cobol", _program(" A.", " GO TO Z.", " Z.", " GOBACK."))+ assert {f.name: f.cognitive for f in fcx.functions}["A"] == 1diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pyindex 543952db3..2dfebbdbb 100644--- a/tests/unit/health/test_scoring_snapshot.py+++ b/tests/unit/health/test_scoring_snapshot.py@@ -124,6 +124,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {"apex_missing_sharing": "apex","apex_hardcoded_id": "apex","apex_see_all_data": "apex",+ "cobol_unstructured_flow": "cobol",}