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): treat CICS-defined programs as entry points and report paragraphs nothing reaches (#4461)
Raghav Chamadiya2328b5871787
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 9cfd43374..ea7461901 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -957,7 +957,7 @@ The analyzer runs after `GitIndexer` during init (Step 3.6) and optionally durin**Finding types:**- `unreachable_file`: file with `in_degree == 0`, not an entry point, test, or config- `unused_export`: public symbol with no incoming edges (but file IS imported)-- `unused_internal`: private symbol with no `calls` edges from same file+- `unused_internal`: private symbol with no `calls` edges from same file; a COBOL paragraph is judged from the program's source text instead- `zombie_package`: monorepo package with no incoming `inter_package` edges**Confidence scoring (conservative: when in doubt, do NOT flag):**diff --git a/docs/architecture/dead-code.md b/docs/architecture/dead-code.mdindex ee05cdf5b..68687dad5 100644--- a/docs/architecture/dead-code.md+++ b/docs/architecture/dead-code.md@@ -146,7 +146,9 @@ only at `>= 0.7` with no risk factor.`unused_internal`: private symbols with no `calls` edge and no cross-fileimporter, base `0.65`, never deletion-ready. Hidden on default surfaces by-`finding_registry.py` (measured 0.5% precision, 1,511 findings).+`finding_registry.py` (measured 0.5% precision, 1,511 findings). A COBOL+paragraph is judged from the program's source text instead of edges+(`cobol_paragraphs.py`), at `0.30`.`zombie_package`: a top-level directory with no inter-package import edges,base `0.50`, never deletion-ready. `_NEVER_PACKAGE_DIRS` skips non-packagediff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 8d89e67b7..85cd96143 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -73,8 +73,11 @@ within each sfdx project's namespace.Scala, Elixir and F# have dedicated import resolvers with known gaps; see[Limits](#limits).-\* COBOL is excluded from dead-code claims: JCL, schedulers and dynamic program-calls are entry paths the repository graph cannot observe.+\* COBOL files and programs get no dead-code claims: schedulers, region+definitions outside the repo and dynamic program calls are entry paths the+repository graph cannot observe. The one COBOL claim is a paragraph that+nothing names and nothing falls through into, at low confidence and never+deletion-ready.The COBOL and Apex grammars download on first use; offline, set`REPOWISE_GRAMMAR_DIR` to a pre-staged grammar cache. `repowise doctor` reportswhether it is cached.@@ -92,6 +95,10 @@ its program and the copybooks it copies; `CALL`, `LINK` and `XCTL` bind to aunique PROGRAM-ID. JCL (`.jcl`, `.prc`, `.proc`) links each job step to theprogram or PROC it runs, which makes that program an entry point, and BMSmapsets (`.bms`) are linked from the programs that send or receive their maps.+CICS CSD definitions, in a `.csd` file or a DFHCSDUP step's in-stream input,+link each defined program and each transaction's program, which makes it an+entry point. `EXEC CICS RETURN` and `START` with a `TRANSID` link to the+program that transaction runs when every definition of it agrees.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-onlycopybooks have no functions to flag.diff --git a/packages/core/src/repowise/core/analysis/dead_code/cobol_paragraphs.py b/packages/core/src/repowise/core/analysis/dead_code/cobol_paragraphs.pynew file mode 100644index 000000000..4fe4febe6--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/cobol_paragraphs.py@@ -0,0 +1,251 @@+"""COBOL paragraphs that no flow of control reaches: the only COBOL dead-code claim.++COBOL files and programs stay exempt (``dead_code_exempt``): a scheduler, a+CICS region definition the repo does not hold, a dynamic ``CALL`` or a web+service can run any program. Inside one program every path is in the text, so+a paragraph is reported when all of these hold:++* its name appears nowhere else in the program or the copybooks it copies, so+ no ``PERFORM``, ``THRU`` bound, ``GO TO``, ``ALTER``, ``SORT`` procedure or+ ``EXEC CICS HANDLE`` names it;+* it is not the first paragraph of the procedure division or of a section;+* the paragraph before it ends in a sentence whose last statement is an+ unconditional ``GOBACK``, ``STOP RUN``, ``GO TO`` or ``EXEC CICS RETURN`` /+ ``XCTL`` (without ``RESP`` or ``NOHANDLE``), so nothing falls through into it;+* the file holds one program, with no ``DECLARATIVES``, ``ENTRY``,+ ``IGNORE CONDITION`` or ``REPLACE``, and every procedure-division ``COPY``+ (and every ``COPY`` inside those, transitively) resolved and free of+ ``REPLACING``.++Any doubt drops the paragraph (recall is the price). A finding is low+confidence and never deletion-ready.+"""++from __future__ import annotations++import re+from pathlib import PurePosixPath+from typing import TYPE_CHECKING++from repowise.core.ingestion.cobol import CopyStatement, code_view, copy_statements++from .constants import _is_fixture_path+from .models import DeadCodeFindingData, DeadCodeKind+from .risk_factors import path_risk_factors++if TYPE_CHECKING:+ import networkx as nx++ from .analyzer import DeadCodeAnalyzer++#: Low tier: below the stored floor, so only a live run with a lower+#: ``--min-confidence`` shows one.+COBOL_PARAGRAPH_CONFIDENCE = 0.3++_PROCEDURE = re.compile(r"\bPROCEDURE\s+DIVISION\b", re.IGNORECASE)+_HEADER = re.compile(+ r"^ {7,10}(?P<name>[A-Z0-9][A-Z0-9-]*)(?P<section>\s+SECTION)?\s*\.[ \t\r]*$",+ re.IGNORECASE | re.MULTILINE,+)+# A verb or scope terminator alone in area A is no paragraph. Only the reserved+# terminators: ``END-PROGRAM.`` is a legal (and common) paragraph name.+_NOT_A_NAME = frozenset(+ {"EXIT", "GOBACK", "CONTINUE"}+ | {+ f"END-{verb}"+ for verb in (+ "ACCEPT", "ADD", "CALL", "COMPUTE", "DELETE", "DISPLAY", "DIVIDE", "EVALUATE",+ "EXEC", "IF", "INVOKE", "JSON", "MULTIPLY", "PERFORM", "READ", "RECEIVE", "RETURN",+ "REWRITE", "SEARCH", "START", "STRING", "SUBTRACT", "UNSTRING", "WRITE", "XML",+ )+ }+)+# ``REPLACE`` rewrites text, so a paragraph can be named by a word no line spells.+_UNSAFE_PROGRAM = re.compile(+ r"\bDECLARATIVES\b|(?<![\w-])ENTRY\s+['\"]|\bIGNORE\s+CONDITION\b|(?<![\w-])REPLACE(?![\w-])",+ re.IGNORECASE,+)+_LITERAL = re.compile(r"'[^'\n]*'|\"[^\"\n]*\"")+_EXEC = re.compile(r"\bEXEC\s+(?:CICS|SQL|SQLIMS|DLI)\b.*?\bEND-EXEC\b", re.IGNORECASE | re.DOTALL)+_SENTENCE_END = re.compile(r"\.(?=\s)")+_TERMINAL = re.compile(+ r"(?:\bGOBACK|\bSTOP RUN|\bGO (?:TO )?[A-Z0-9][A-Z0-9-]*"+ r"|\bEXEC CICS (?:RETURN|XCTL)\b(?:(?!END-EXEC).)*\bEND-EXEC)$"+)+_CONDITIONAL = re.compile(+ r"\bNEXT SENTENCE\b|\bAT END\b|\bINVALID\b|\bSIZE ERROR\b|\bOVERFLOW\b|\bEXCEPTION\b|\bSEARCH\b"+)+++def unreachable_paragraphs(code: str, copied: dict[str, str]) -> list[tuple[str, int, int]]:+ """``(name, start line, end line)`` per paragraph of *code* nothing reaches.++ *code* is a program's code view; *copied* maps each member it copies that+ resolved to that member's code view.+ """+ procedure = _procedure(code, copied)+ if procedure is None:+ return []+ start, copies = procedure+ headers = [h for h in _HEADER.finditer(code, start) if _is_name(h.group("name"))]+ haystack = "\n".join([code, *copied.values()])+ return [+ (headers[k].group("name").upper(), *_span(code, headers, k, copies))+ for k in range(1, len(headers))+ if _is_unreachable(code, headers, k, haystack)+ ]+++def _procedure(code: str, copied: dict[str, str]) -> tuple[int, list[CopyStatement]] | None:+ """Where the procedure division starts and its COPYs, or ``None`` if it is not judged."""+ divisions = list(_PROCEDURE.finditer(code))+ if len(divisions) != 1 or _UNSAFE_PROGRAM.search(code):+ return None+ start = divisions[0].end()+ line_of_start = code.count("\n", 0, start) + 1+ copies = [c for c in copy_statements(code) if c.line >= line_of_start]+ return (start, copies) if _closed(copies, copied) else None+++def _is_unreachable(code: str, headers: list[re.Match[str]], k: int, haystack: str) -> bool:+ """Whether paragraph *k* opens no section, is never named, and is never fallen into."""+ header, previous = headers[k], headers[k - 1]+ if header.group("section") or previous.group("section"):+ return False+ # The cheap fall-through check first: the name scan below reads the whole program.+ if not _ends_in_transfer(code[previous.end() : header.start()]):+ return False+ name = re.escape(header.group("name"))+ mentions = re.findall(rf"(?<![\w-]){name}(?![\w-])", haystack, re.IGNORECASE)+ return len(mentions) == 1+++def _span(+ code: str, headers: list[re.Match[str]], k: int, copies: list[CopyStatement]+) -> tuple[int, int]:+ """Paragraph *k*'s first and last line: up to the next header or the next COPY (a+ procedure copybook opens its own paragraph), without the blank lines before it."""+ first = code.count("\n", 0, headers[k].start()) + 1+ last = code.count("\n", 0, headers[k + 1].start()) if k + 1 < len(headers) else None+ last = min([c.line - 1 for c in copies if c.line > first] + [last or code.count("\n") + 1])+ lines = code.split("\n")+ while last > first and not lines[last - 1].strip():+ last -= 1+ return first, last+++def _is_name(word: str) -> bool:+ """A header word that can name a paragraph: no scope terminator or bare verb."""+ return word.upper() not in _NOT_A_NAME+++def _closed(copies: list[CopyStatement], copied: dict[str, str]) -> bool:+ """Whether the code *copies* bring in is all read, transitively, and copied verbatim.++ Every member, and every member those copy in turn, must have resolved, and+ none may use ``REPLACING`` or ``REPLACE``: a rewritten copybook can name a+ paragraph its text never spells.+ """+ pending, seen = list(copies), set()+ while pending:+ statement = pending.pop()+ if statement.replacing or statement.member not in copied:+ return False+ if statement.member in seen:+ continue+ seen.add(statement.member)+ member = copied[statement.member]+ if _UNSAFE_PROGRAM.search(member):+ return False+ pending.extend(copy_statements(member))+ return True+++def _ends_in_transfer(body: str) -> bool:+ """Whether *body* (a paragraph) ends in a sentence that always leaves it."""+ text = _LITERAL.sub(lambda m: "X" * len(m.group(0)), body).rstrip()+ if not text.endswith("."):+ return False+ text = text[:-1]+ sentence = " ".join(_SENTENCE_END.split(text)[-1].split()).upper()+ terminal = _TERMINAL.search(sentence)+ if terminal is None or re.search(r"\bRESP2?\b|\bNOHANDLE\b", terminal.group(0)):+ return False+ before = _EXEC.sub(" ", sentence[: terminal.start()])+ if _CONDITIONAL.search(before):+ return False+ return all(+ len(re.findall(rf"(?<![\w-]){opener}(?![\w-])", before))+ == len(re.findall(rf"(?<![\w-])END-{opener}(?![\w-])", before))+ for opener in ("IF", "EVALUATE")+ )+++def _copied_closure(graph: nx.DiGraph, path: str) -> set[str]:+ """Every file *path* imports, directly or through the copybooks it copies."""+ found: set[str] = set()+ pending = [path]+ while pending:+ node = pending.pop()+ for dst in graph.successors(node):+ edge = graph.edges[node, dst]+ if edge.get("edge_type") == "imports" and dst not in found and dst != path:+ found.add(dst)+ pending.append(dst)+ return found+++def unreachable_paragraph_findings(+ ctx: DeadCodeAnalyzer, whitelist: set[str]+) -> list[DeadCodeFindingData]:+ """An unused-internal finding per COBOL paragraph :func:`unreachable_paragraphs` returns."""+ sources = ctx._source_map+ findings: list[DeadCodeFindingData] = []+ for path in _judged_programs(ctx, whitelist):+ copied = {+ PurePosixPath(member).stem.upper(): code_view(sources[member])+ for member in _copied_closure(ctx.graph, path)+ if member in sources+ }+ for name, start, end in unreachable_paragraphs(code_view(sources[path]), copied):+ findings.append(_finding(ctx, path, name, start, end))+ return findings+++def _judged_programs(ctx: DeadCodeAnalyzer, whitelist: set[str]) -> list[str]:+ """The COBOL files with read source that no test, fixture or whitelist rule exempts."""+ return [+ path+ for path, data in ctx.graph.nodes(data=True)+ if _is_cobol_source(ctx, path, data)+ and not (data.get("is_test") or _is_fixture_path(path))+ and not ctx._should_never_flag(path, whitelist)+ ]+++def _is_cobol_source(ctx: DeadCodeAnalyzer, path: str, data: dict) -> bool:+ is_cobol_file = data.get("node_type") == "file" and data.get("language") == "cobol"+ return is_cobol_file and path in ctx._source_map+++def _finding(+ ctx: DeadCodeAnalyzer, path: str, name: str, start: int, end: int+) -> DeadCodeFindingData:+ return DeadCodeFindingData(+ kind=DeadCodeKind.UNUSED_INTERNAL,+ file_path=path,+ symbol_name=name,+ symbol_kind="function",+ confidence=COBOL_PARAGRAPH_CONFIDENCE,+ reason=f"Paragraph '{name}' is never named and nothing falls through into it",+ evidence=[+ f"No statement in the program or its copybooks names '{name}'",+ "The paragraph before it always transfers control away",+ ],+ safe_to_delete=False,+ risk_factors=list(path_risk_factors(path)),+ lines=end - start + 1,+ start_line=start,+ end_line=end,+ **ctx._git_fields(path),+ )diff --git a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.pyindex 4d36b80e8..3cc65120b 100644--- a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py+++ b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py@@ -1,10 +1,15 @@-"""The unused-internal pass: private symbols no call, reference or override reaches."""+"""The unused-internal pass: private symbols no call, reference or override reaches.++COBOL paragraphs are judged from the program's source text instead, by+``cobol_paragraphs.py``.+"""from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom ..apex_reachability import is_apex_entry_member+from ..cobol_paragraphs import unreachable_paragraph_findingsfrom ..constants import _DEAD_CODE_EXEMPT_LANGUAGES, _is_fixture_pathfrom ..contract_methods import is_contract_methodfrom ..decorator_rules import _declared_deliberately_unused, _is_framework_registered@@ -19,7 +24,7 @@ if TYPE_CHECKING:# Rust: the compiler's ``dead_code`` lint already reports these, with macro# expansion and types a static graph cannot match. The exempt languages# (COBOL) are entered by a runtime the graph cannot see, as in the file and-# export passes.+# export passes; a COBOL paragraph is judged by ``cobol_paragraphs`` instead._UNJUDGED_LANGUAGES = _DEAD_CODE_EXEMPT_LANGUAGES | {"rust"}@@ -83,7 +88,8 @@ class UnusedInternalPass:))- return findings+ # COBOL's one claim, read from source rather than call edges.+ return findings + unreachable_paragraph_findings(self.ctx, whitelist)def _is_internal_candidate(self, node_data: dict, dynamic_patterns: tuple[str, ...], whitelist: set[str]diff --git a/packages/core/src/repowise/core/ingestion/cobol/cics.py b/packages/core/src/repowise/core/ingestion/cobol/cics.pyindex dde485cba..45b4721f4 100644--- a/packages/core/src/repowise/core/ingestion/cobol/cics.py+++ b/packages/core/src/repowise/core/ingestion/cobol/cics.py@@ -1,9 +1,11 @@-"""CICS ``LINK`` / ``XCTL`` programs and ``SEND`` / ``RECEIVE MAP`` mapsets, with constant tracking.+"""CICS ``LINK`` / ``XCTL`` programs, ``SEND`` / ``RECEIVE MAP`` mapsets and+``RETURN`` / ``START`` transactions, with constant tracking.``PROGRAM('X')`` names its target. ``PROGRAM(VAR)`` names every value theprogram moves into ``VAR`` that is a literal or a constant (a data item with a``VALUE`` literal that nothing reassigns). Any other assignment makes the-target dynamic, reported as such and never guessed. ``MAPSET`` reads the same way.+target dynamic, reported as such and never guessed. ``MAPSET`` and ``TRANSID``+read the same way.Ceiling: only the program's own text is read, so a constant defined in acopybook, or a value arriving through a group move (a COMMAREA), is dynamic.@@ -28,6 +30,9 @@ _PROGRAM = re.compile(r"\bPROGRAM" + _OPERAND, re.IGNORECASE)_MAP_COMMAND = re.compile(r"^\s*(SEND|RECEIVE)\s+MAP\b", re.IGNORECASE)_MAPSET = re.compile(r"\bMAPSET" + _OPERAND, re.IGNORECASE)_MAP = re.compile(r"\bMAP" + _OPERAND, re.IGNORECASE)+# ``STARTBR`` is a browse, not a START.+_TRANSID_COMMAND = re.compile(r"^\s*(RETURN|START)\b", re.IGNORECASE)+_TRANSID = re.compile(r"\bTRANSID" + _OPERAND, re.IGNORECASE)_MOVE = re.compile(# The receivers are a lookahead, so a MOVE inside them is matched on its own.rf"(?<![\w-])MOVE\s+(?P<src>{_LITERAL}|{_NAME}(?:\s*\([^)]*\))?)\s+TO\s+(?=(?P<dst>[^.]*))",@@ -105,6 +110,11 @@ def mapset_uses(code: str) -> list[CicsTarget]:return _cics_targets(code, _MAP_COMMAND, _MAPSET, fallback=_MAP)+def transid_uses(code: str) -> list[CicsTarget]:+ """Every RETURN/START naming a TRANSID in *code*: the transaction the region runs next."""+ return _cics_targets(code, _TRANSID_COMMAND, _TRANSID)++def _cics_targets(code: str,command: re.Pattern[str],diff --git a/packages/core/src/repowise/core/ingestion/cobol/csd.py b/packages/core/src/repowise/core/ingestion/cobol/csd.pynew file mode 100644index 000000000..ff8f537ac--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/cobol/csd.py@@ -0,0 +1,131 @@+"""CICS CSD resource definitions (DFHCSDUP input): the programs and transactions a region runs.++Read from a ``.csd`` file or from a JCL step's in-stream data. A command starts+on a line whose first word stands alone (not ``WORD(``) and runs until the+next such line; a ``*`` in column 1 is a comment. Commands, resource types and+the ``PROGRAM`` attribute may be abbreviated as DFHCSDUP allows (``DEF+TRANS(T) PROG(P)``). ``DEFINE TRANSACTION(T) ... PROGRAM(P)`` names the+program transaction T runs; an ``ALTER`` naming another program adds it, so a+transaction two programs can run links to neither. ``DELETE`` is ignored, which+only keeps a deleted program a root.++Ceiling: a line opening with a bare word ends the command, so an attribute+value wrapped onto a new line drops the rest of that command (a missed link,+never a wrong one).+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass++from ..models import FileInfo, ParsedFile, Symbol++# A line opening with a bare word starts a command; ``DELETE(YES)`` is an attribute.+_COMMAND = re.compile(r"^\s*([A-Z]+)(?=\s|$)", re.IGNORECASE)+_RESOURCE = re.compile(+ r"^\s*(?P<command>[A-Z]+)\s+(?P<resource>[A-Z]+)\s*\(\s*(?P<name>[^()\s]+)\s*\)(?P<rest>.*)",+ re.IGNORECASE | re.DOTALL,+)+_PROGRAM_ATTR = re.compile(r"(?<![\w-])PROG[A-Z]*\s*\(\s*(?P<name>[^()\s]+)\s*\)", re.IGNORECASE)+++def _abbreviates(word: str, full: str, shortest: int) -> bool:+ """Whether *word* is *full* or a DFHCSDUP abbreviation of it."""+ word = word.upper()+ return len(word) >= shortest and full.startswith(word)+++def _command(word: str) -> str | None:+ if _abbreviates(word, "DEFINE", 3) or _abbreviates(word, "USERDEFINE", 5):+ return "DEFINE"+ return "ALTER" if _abbreviates(word, "ALTER", 3) else None+++def _resource(word: str) -> str:+ if _abbreviates(word, "TRANSACTION", 5):+ return "TRANSACTION"+ if _abbreviates(word, "PROGRAM", 4):+ return "PROGRAM"+ return word.upper()+++@dataclass(frozen=True)+class CsdDefinition:+ """One ``DEFINE`` or ``ALTER``: its resource type and name, and a transaction's program."""++ resource: str+ name: str+ line: int+ program: str | None = None+ command: str = "DEFINE"+++def read_csd(lines: Iterable[tuple[int, str]]) -> list[CsdDefinition]:+ """Every ``DEFINE`` and ``ALTER`` in *lines* (``(line number, text)``), continuations joined."""+ commands: list[tuple[int, str]] = []+ for number, line in lines:+ if line.startswith("*") or not line.strip():+ continue+ if _COMMAND.match(line) or not commands:+ commands.append((number, line))+ else:+ commands[-1] = (commands[-1][0], f"{commands[-1][1]} {line}")+ out: list[CsdDefinition] = []+ for number, text in commands:+ m = _RESOURCE.match(text)+ command = _command(m.group("command")) if m else None+ if m is None or command is None:+ continue+ resource = _resource(m.group("resource"))+ program = _PROGRAM_ATTR.search(m.group("rest")) if resource == "TRANSACTION" else None+ out.append(+ CsdDefinition(+ resource,+ m.group("name").upper(),+ number,+ program.group("name").upper() if program else None,+ command,+ )+ )+ return out+++def defined_programs(definitions: list[CsdDefinition]) -> list[str]:+ """The programs *definitions* make runnable: each PROGRAM, and each transaction's program."""+ names = {d.name for d in definitions if d.resource == "PROGRAM"}+ names |= {d.program for d in definitions if d.program}+ return sorted(names)+++def parse_csd_file(file_info: FileInfo, source: bytes) -> ParsedFile:+ """Each defined resource as a symbol: ``TRANSACTION CAUP PROGRAM(COACTUPC)``."""+ lines = source.decode("utf-8", errors="replace").splitlines()+ definitions = [d for d in read_csd(enumerate(lines, 1)) if d.command == "DEFINE"]+ symbols = [+ Symbol(+ id=f"{file_info.path}::{d.resource}:{d.name}",+ name=d.name,+ qualified_name=f"{d.resource}:{d.name}",+ kind="variable",+ signature=f"{d.resource} {d.name}" + (f" PROGRAM({d.program})" if d.program else ""),+ start_line=d.line,+ end_line=next_line - 1,+ docstring=None,+ language="csd",+ )+ for d, next_line in zip(+ definitions,+ [d.line for d in definitions[1:]] + [len(lines) + 1],+ strict=True,+ )+ ]+ return ParsedFile(+ file_info=file_info,+ symbols=symbols,+ imports=[],+ exports=[s.name for s in symbols],+ docstring=None,+ parse_errors=[],+ )diff --git a/packages/core/src/repowise/core/ingestion/cobol/jcl.py b/packages/core/src/repowise/core/ingestion/cobol/jcl.pyindex 9674f71a7..70255a4ef 100644--- a/packages/core/src/repowise/core/ingestion/cobol/jcl.py+++ b/packages/core/src/repowise/core/ingestion/cobol/jcl.py@@ -2,7 +2,10 @@Read line by line: ``//*`` comments are skipped and a statement continued onthe next ``//`` line is joined to it. A step runs ``PGM=X`` or a procedure-(``EXEC X`` / ``EXEC PROC=X``). In-stream data (``DD *``) is skipped.+(``EXEC X`` / ``EXEC PROC=X``). In-stream data (``DD *`` / ``DD DATA``, up to+``/*``, the next ``//`` statement, or its ``DLM=`` delimiter) is kept apart, for+the CSD definitions a DFHCSDUP step reads there. Ceiling: data under ``DLM=``+still passes the statement joiner, so a ``//*`` data line is dropped."""from __future__ import annotations@@ -17,6 +20,7 @@ _STATEMENT = re.compile(rf"^//(?P<name>{_NAME})?\s+(?P<op>\S+)\s*(?P<operands>.*_PGM = re.compile(rf"^PGM=(?P<name>{_NAME})\b", re.I)_PROC = re.compile(rf"^(?:PROC=)?(?P<name>{_NAME})\s*(?:,|$)", re.I)_IN_STREAM = re.compile(r"\bDD\s+(\*|DATA)", re.I)+_DELIMITER = re.compile(r"\bDLM=(?:'(?P<quoted>[^']{2})'|(?P<plain>[^\s,']{2}))", re.I)@dataclass@@ -35,16 +39,23 @@ class JclMember:jobs: list[str] = field(default_factory=list)procedures: list[str] = field(default_factory=list)steps: list[JclStep] = field(default_factory=list)+ in_stream: list[tuple[int, str]] = field(default_factory=list)def read_jcl(text: str) -> JclMember:member = JclMember()lines = text.splitlines()- in_stream = False+ # While in-stream: the prefix that ends the data ("/" for ``/*`` and ``//``).+ end_of_data: str | None = Nonefor number, statement in _statements(lines):- if in_stream and not statement.startswith("//"):- continue- in_stream = False+ if end_of_data is not None:+ if not statement.startswith(end_of_data):+ member.in_stream.append((number, statement))+ continue+ if end_of_data != "/":+ end_of_data = None+ continue+ end_of_data = Nonem = _STATEMENT.match(statement)if m is None:continue@@ -67,7 +78,8 @@ def read_jcl(text: str) -> JclMember:step.procedure = proc.group("name").upper() if proc else Nonemember.steps.append(step)elif op == "DD" and _IN_STREAM.search(f"DD {operands}"):- in_stream = True+ delimiter = _DELIMITER.search(operands)+ end_of_data = (delimiter.group("quoted") or delimiter.group("plain")) if delimiter else "/"return memberdiff --git a/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py b/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.pyindex 0894cca51..3eecd0cdb 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py@@ -1,14 +1,20 @@-"""Mainframe edges: JCL steps to programs and PROCs, COBOL programs to BMS mapsets.+"""Mainframe edges: JCL steps to programs and PROCs, CSD definitions to programs,+COBOL programs to BMS mapsets and to the programs their TRANSIDs run.* ``EXEC PGM=X`` -> the COBOL program whose PROGRAM-ID is X, marked areachability root: a batch program runs because a job names it.* ``EXEC P`` / ``EXEC PROC=P`` -> the procedure member P, by file stem first,then by a unique ``//P PROC`` declaration.+* ``DEFINE PROGRAM(X)`` or ``DEFINE TRANSACTION(T) PROGRAM(X)``, in a ``.csd``+ file or a JCL step's in-stream data -> program X, marked a reachability+ root: CICS runs it by its definition.* ``EXEC CICS SEND|RECEIVE MAP ... MAPSET(M)`` -> the BMS source defining M.+* ``EXEC CICS RETURN|START TRANSID(T)`` -> the program transaction T runs,+ when every definition of T names the same one.A job member is an entry point. Names fold case; two equally near candidatesbind neither, and a utility (``IDCAMS``, ``SORT``) the repo does not hold links-to nothing.+to nothing. A program returning to its own transaction gets no edge."""from __future__ import annotations@@ -17,7 +23,8 @@ from pathlib import PurePosixPathfrom typing import TYPE_CHECKING, Anyfrom ..cobol import code_view-from ..cobol.cics import mapset_uses+from ..cobol.cics import mapset_uses, transid_uses+from ..cobol.csd import CsdDefinition, defined_programs, read_csdfrom ..cobol.jcl import read_jclfrom ..resolvers.lwc import nearestfrom .aura import _file_edge@@ -64,6 +71,17 @@ def _proc_files(parsed_files: dict[str, Any]) -> dict[str, list[str]]:return out+def _csd_definitions(path: str, parsed: Any, source_map: dict[str, bytes]) -> list[CsdDefinition]:+ """A ``.csd`` file's definitions, or those in a JCL member's in-stream data."""+ language = parsed.file_info.language+ if language not in ("csd", "jcl"):+ return []+ text = source_text(path, parsed, source_map)+ if language == "csd":+ return read_csd(enumerate(text.splitlines(), 1))+ return read_csd(read_jcl(text).in_stream)++def _add_mainframe_edges(graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext) -> int:@@ -71,7 +89,21 @@ def _add_mainframe_edges(programs = _by_name(parsed_files, "cobol", "module")mapsets = _by_name(parsed_files, "bms", "module")procs = _proc_files(parsed_files)+ definitions = {+ path: defs+ for path in sorted(parsed_files)+ if (defs := _csd_definitions(path, parsed_files[path], source_map))+ }+ # Transaction -> every program a definition of it names (regions may differ).+ transactions: dict[str, set[str]] = {}+ for defs in definitions.values():+ for d in defs:+ if d.program:+ transactions.setdefault(d.name, set()).add(d.program)count = 0+ for path, defs in definitions.items():+ for name in defined_programs(defs):+ count += _root_edge(graph, path, nearest(programs.get(name, []), path))for path in sorted(parsed_files):parsed = parsed_files[path]language = parsed.file_info.language@@ -81,27 +113,43 @@ def _add_mainframe_edges(graph.nodes[path]["is_entry_point"] = Truefor step in member.steps:if step.program:- target = nearest(programs.get(step.program, []), path)- if target and target in graph:- graph.nodes[target]["is_reachability_root"] = True- count += _file_edge(graph, path, target, set())+ count += _root_edge(graph, path, nearest(programs.get(step.program, []), path))elif step.procedure:target = nearest(procs.get(step.procedure, []), path)if target:count += _file_edge(graph, path, target, set())- elif language == "cobol" and mapsets:+ elif language == "cobol" and (mapsets or transactions):raw = source_map.get(path) or source_text(path, parsed, source_map).encode()- for use in mapset_uses(code_view(raw)):+ code = code_view(raw)+ for use in mapset_uses(code):for name in use.targets:target = nearest(mapsets.get(name, []), path)if target:count += _file_edge(graph, path, target, set())+ for use in transid_uses(code):+ # A TRANSID also set at runtime may name any transaction: no edge.+ for transid in () if use.dynamic else use.targets:+ runs = transactions.get(transid, set())+ if len(runs) == 1:+ target = nearest(programs.get(next(iter(runs)), []), path)+ if target:+ count += _file_edge(graph, path, target, set())return count+def _root_edge(graph: nx.DiGraph, src: str, program: str | None) -> int:+ """An edge from *src* to *program*, which something outside the source runs."""+ if program is None or program not in graph:+ return 0+ graph.nodes[program]["is_reachability_root"] = True+ return _file_edge(graph, src, program, set())++class _MainframeHandler:def detect(self, dctx: DetectionContext) -> bool:- return any(p.file_info.language in ("jcl", "bms") for p in dctx.parsed_files.values())+ return any(+ p.file_info.language in ("jcl", "bms", "csd") for p in dctx.parsed_files.values()+ )def add_edges(self,diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex 359bab91b..9abbbd099 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -21,6 +21,7 @@ from .clojure import SPEC as _CLOJUREfrom .cobol import SPEC as _COBOLfrom .cpp import SPEC as _CPPfrom .crystal import SPEC as _CRYSTAL+from .csd import SPEC as _CSDfrom .csharp import SPEC as _CSHARPfrom .dart import SPEC as _DARTfrom .dlang import SPEC as _DLANG@@ -160,9 +161,11 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (# Salesforce object/field metadata and saved SOQL queries._SALESFORCE_OBJECT,_SOQL,- # Mainframe job control and CICS screen maps; edges from framework_edges/mainframe.py.+ # Mainframe job control, CICS screen maps and CSD definitions; edges from+ # framework_edges/mainframe.py._JCL,_BMS,+ _CSD,# -----------------------------------------------------------------# Extra languages — git blame coverage only (passthrough + is_code)# These exist so git_indexer tracks their history even thoughdiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/csd.py b/packages/core/src/repowise/core/ingestion/languages/specs/csd.pynew file mode 100644index 000000000..db570918e--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/csd.py@@ -0,0 +1,16 @@+"""LanguageSpec for CICS CSD definitions (DFHCSDUP input): programs and transactions.++``framework_edges/mainframe.py`` links each defined program, and each+transaction's program, from the CSD. ``is_code=False``, as for job control.+"""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="csd",+ display_name="CICS CSD",+ extensions=frozenset({".csd"}),+ is_code=False,+ is_passthrough=True,+ color_hex="#3E6A8C",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 330468b86..122f336c7 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -98,6 +98,7 @@ LanguageTag = Literal["soql","jcl","bms",+ "csd","unknown",]diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.pyindex a7fcd24b6..2e14a3b2c 100644--- a/packages/core/src/repowise/core/ingestion/special_handlers.py+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py@@ -18,6 +18,7 @@ from pathlib import Pathimport structlogfrom .cobol.bms import parse_bms_file+from .cobol.csd import parse_csd_filefrom .cobol.jcl import parse_jcl_filefrom .models import FileInfo, Import, ParsedFile, Symbolfrom .salesforce_flow import parse_flow_file@@ -40,6 +41,7 @@ SPECIAL_HANDLER_LANGUAGES = frozenset("soql","jcl","bms",+ "csd",})@@ -61,6 +63,7 @@ def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:"soql": parse_soql_file,"jcl": parse_jcl_file,"bms": parse_bms_file,+ "csd": parse_csd_file,}.get(lang, _parse_unknown)try:return handler(file_info, source)diff --git a/scripts/cobol_acceptance.py b/scripts/cobol_acceptance.pyindex 67dd4cf79..58cb92db0 100644--- a/scripts/cobol_acceptance.py+++ b/scripts/cobol_acceptance.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport argparseimport collections+import itertoolsimport jsonimport osimport re@@ -24,6 +25,8 @@ _PROGRAM_EXTS = {".cbl", ".cob", ".cobol"}_COPYBOOK_EXTS = {".cpy", ".dcl"}_JCL_EXTS = {".jcl", ".prc", ".proc"}_BMS_EXTS = {".bms"}+_CSD_EXTS = {".csd"}+_CSD_COMMAND = re.compile(r"^\s*(?:DEFINE|ADD|ALTER|APPEND|COPY|DELETE|LIST|REMOVE)\s", re.I | re.M)_NOT_A_PARAGRAPH = {"UNTIL", "VARYING", "WITH", "TEST", "FOREVER", "THRU", "THROUGH"}_STRUCTURAL = ("calls", "imports", "framework")@@ -31,7 +34,7 @@ _STRUCTURAL = ("calls", "imports", "framework")def _walk(root: str) -> dict[str, dict[str, list[str]]]:"""``{kind: {STEM: [relpath, ...]}}`` for programs, copybooks, JCL and BMS."""found: dict[str, dict[str, list[str]]] = {- k: collections.defaultdict(list) for k in ("program", "copybook", "jcl", "bms")+ k: collections.defaultdict(list) for k in ("program", "copybook", "jcl", "bms", "csd")}for dirpath, dirnames, filenames in os.walk(root):dirnames[:] = [d for d in dirnames if d not in (".git", ".repowise")]@@ -48,6 +51,8 @@ def _walk(root: str) -> dict[str, dict[str, list[str]]]:if ext in _JCL_EXTSelse "bms"if ext in _BMS_EXTS+ else "csd"+ if ext in _CSD_EXTSelse None)if kind:@@ -70,9 +75,9 @@ def _code_lines(path: str) -> list[tuple[int, str, str]]:def truth(root: str) -> dict:files = _walk(root)progs, cpys, jcls, bms = (files[k] for k in ("program", "copybook", "jcl", "bms"))+ transactions = _csd_truth(root, files, progs, pairs := collections.defaultdict(set))paragraphs: set[tuple[str, str]] = set()performs: set[tuple[str, str]] = set()- pairs: dict[str, set[tuple[str, str]]] = collections.defaultdict(set)for rels in progs.values():for rel in rels:@@ -116,6 +121,18 @@ def truth(root: str) -> dict:for dst in progs.get(target, []):if dst != rel:pairs["cics"].add((rel, dst))+ for m in re.finditer(+ r"EXEC\s+CICS\s+(?:RETURN|START)\b(.*?)END-EXEC", text, re.I | re.S+ ):+ tm = re.search(r"TRANSID\s*\(\s*('?)([A-Z0-9#@$-]+)'?\s*\)", m.group(1), re.I)+ if not tm:+ continue+ name = tm.group(2).upper()+ for tran in {name} if tm.group(1) else literals.get(name, set()):+ runs = transactions.get(tran, set())+ for dst in progs.get(next(iter(runs)), []) if len(runs) == 1 else []:+ if dst != rel:+ pairs["transid"].add((rel, dst))for m in re.finditer(r"EXEC\s+CICS\s+(?:SEND|RECEIVE)\s+MAP\s*\(.*?END-EXEC", text, re.I | re.S):@@ -142,6 +159,44 @@ def truth(root: str) -> dict:}+def _csd_truth(root: str, files: dict, progs: dict, pairs: dict) -> dict[str, set[str]]:+ """CSD pairs (definer, program) into *pairs*; returns ``{TRANSACTION: {PROGRAM, ...}}``.++ Definitions are read from ``.csd`` files and from JCL in-stream data+ (``DD *`` up to ``/*`` or the next ``//`` statement).+ """+ transactions: dict[str, set[str]] = collections.defaultdict(set)+ for kind in ("csd", "jcl"):+ for rel in (r for rels in files[kind].values() for r in rels):+ with open(os.path.join(root, rel), encoding="latin-1") as fh:+ raw = fh.read().splitlines()+ if kind == "jcl":+ kept, inside = [], False+ for line in raw:+ if line.startswith("/"):+ inside = bool(re.search(r"\bDD\s+(\*|DATA)", line, re.I))+ elif inside:+ kept.append(line)+ raw = kept+ text = "\n".join(line for line in raw if not line.startswith("*"))+ starts = [m.start() for m in _CSD_COMMAND.finditer(text)] + [len(text)]+ for a, b in itertools.pairwise(starts):+ chunk = text[a:b]+ d = re.match(r"\s*DEFINE\s+(PROGRAM|TRANSACTION)\s*\(\s*(\S+?)\s*\)", chunk, re.I)+ if not d:+ continue+ name = d.group(2).upper()+ if d.group(1).upper() == "TRANSACTION":+ pm = re.search(r"\sPROGRAM\s*\(\s*(\S+?)\s*\)", chunk[d.end() :], re.I)+ if not pm:+ continue+ name = pm.group(1).upper()+ transactions[d.group(2).upper()].add(name)+ for dst in progs.get(name, []):+ pairs["csd"].add((rel, dst))+ return transactions++def _literal_assignments(text: str) -> dict[str, set[str]]:"""``{VAR: {'LIT', ...}}`` from ``VAR ... VALUE 'LIT'``, ``MOVE 'LIT' TO VAR``, and``MOVE CONST TO VAR`` where ``CONST`` has a VALUE literal."""@@ -223,7 +278,7 @@ def metrics(root: str, db: str) -> dict:len(t["pairs"][kind] & (imports if kind in ("copy", "include") else any_pairs)),len(t["pairs"][kind]),)- for kind in ("copy", "include", "call", "cics", "jcl", "bms")+ for kind in ("copy", "include", "call", "cics", "jcl", "bms", "csd", "transid")}return {"cobol_symbols": ix["cobol_symbols"],diff --git a/tests/unit/dead_code/test_cobol_external_entry.py b/tests/unit/dead_code/test_cobol_external_entry.pyindex 97f2dddb5..5a80a4acc 100644--- a/tests/unit/dead_code/test_cobol_external_entry.py+++ b/tests/unit/dead_code/test_cobol_external_entry.py@@ -69,3 +69,143 @@ def test_exempt_language_private_symbol_is_not_an_unused_internal() -> None:{"detect_zombie_packages": False})assert "unused_internal" in {finding.kind for finding in control.findings}+++# A paragraph is reported only when nothing names it and nothing falls into it.+_HEAD = (+ " IDENTIFICATION DIVISION.\n"+ " PROGRAM-ID. PAYROLL.\n"+ " PROCEDURE DIVISION.\n"+ " MAIN-PARA.\n"+ " PERFORM WORK-PARA THRU WORK-EXIT\n"+)+++def _unreachable(body: str, copied: dict[str, str] | None = None) -> list[str]:+ from repowise.core.analysis.dead_code.cobol_paragraphs import unreachable_paragraphs++ return [name for name, _, _ in unreachable_paragraphs(_HEAD + body, copied or {})]+++def test_an_unnamed_paragraph_after_an_unconditional_return_is_unreachable() -> None:+ body = (+ " IF A = 1\n MOVE 2 TO B\n END-IF\n"+ " EXEC CICS RETURN TRANSID('PAY1') END-EXEC\n .\n"+ " MAIN-EXIT.\n EXIT.\n"+ " WORK-PARA.\n GOBACK.\n"+ " WORK-EXIT.\n EXIT.\n"+ )+ assert _unreachable(body) == ["MAIN-EXIT"]+++def test_fall_through_and_named_paragraphs_are_not_reported() -> None:+ cases = {+ # The terminal statement is conditional.+ "conditional": " IF A = 1\n GOBACK.\n NEXT-PARA.\n EXIT.\n",+ "read_at_end": " READ F AT END GOBACK.\n NEXT-PARA.\n EXIT.\n",+ # Control can fall through: no transfer, EXIT PROGRAM, or a RESP that returns.+ "falls": " MOVE 1 TO A.\n NEXT-PARA.\n EXIT.\n",+ "exit_program": " EXIT PROGRAM.\n NEXT-PARA.\n EXIT.\n",+ "resp": " EXEC CICS RETURN RESP(WS-RESP) END-EXEC.\n"+ " NEXT-PARA.\n EXIT.\n",+ "next_sentence": " IF A = 1 NEXT SENTENCE END-IF GOBACK.\n"+ " NEXT-PARA.\n EXIT.\n",+ # Named elsewhere: a GO TO, an ALTER, a CICS handler.+ "go_to": " GOBACK.\n NEXT-PARA.\n GO TO NEXT-PARA.\n",+ "handler": " EXEC CICS HANDLE AID PF3(NEXT-PARA) END-EXEC\n"+ " GOBACK.\n NEXT-PARA.\n EXIT.\n",+ # The first paragraph of a section runs when the section is performed.+ "section": " GOBACK.\n S1 SECTION.\n NEXT-PARA.\n EXIT.\n",+ # A program with an ENTRY can start anywhere.+ "entry": " GOBACK.\n NEXT-PARA.\n ENTRY 'ALT' USING A.\n",+ }+ for case, body in cases.items():+ assert _unreachable(body) == [], case+++def test_a_procedure_copybook_naming_the_paragraph_or_unresolved_keeps_it() -> None:+ body = " GOBACK.\n NEXT-PARA.\n EXIT.\n COPY PROCS.\n"+ assert _unreachable(body) == []+ assert _unreachable(body, {"PROCS": " P2.\n PERFORM NEXT-PARA.\n"}) == []+ assert _unreachable(body, {"PROCS": " P2.\n EXIT.\n"}) == ["NEXT-PARA"]+++def test_cobol_paragraph_findings_are_low_and_never_deletion_ready() -> None:+ path = "cbl/PAYROLL.cbl"+ source = (+ _HEAD + " GOBACK.\n"+ " WORK-PARA.\n EXIT.\n"+ " WORK-EXIT.\n GOBACK.\n"+ " DEAD-PARA.\n DISPLAY 'X'.\n"+ )+ graph = _graph("cobol")+ graph.add_node(path, node_type="file", language="cobol", is_entry_point=False,+ is_test=False, symbol_count=0)+ report = DeadCodeAnalyzer(+ graph, git_meta_map={}, source_map={path: source.encode()}+ ).analyze({"detect_zombie_packages": False, "min_confidence": 0.0})++ assert [(f.kind, f.symbol_name) for f in report.findings] == [("unused_internal", "DEAD-PARA")]+ finding = report.findings[0]+ assert finding.confidence < 0.4+ assert finding.safe_to_delete is False+ assert (finding.start_line, finding.end_line) == (11, 12)+++def test_rewritten_or_unread_copybooks_keep_every_paragraph() -> None:+ body = (+ " GOBACK.\n ACCT-INIT.\n EXIT.\n"+ " COPY PROCS REPLACING ==:P:== BY ==ACCT==.\n"+ )+ assert _unreachable(body, {"PROCS": " P2.\n PERFORM :P:-INIT.\n"}) == []+ replace = " GOBACK.\n ACCT-INIT.\n EXIT.\n REPLACE ==A== BY ==B==.\n"+ assert _unreachable(replace) == []+ nested = " GOBACK.\n NEXT-PARA.\n EXIT.\n COPY OUTER.\n"+ outer = " P2.\n EXIT.\n COPY INNER.\n"+ # A copybook copied by a procedure copybook is searched too, and must resolve.+ assert _unreachable(nested, {"OUTER": outer}) == []+ assert _unreachable(nested, {"OUTER": outer, "INNER": " PERFORM NEXT-PARA.\n"}) == []+ assert _unreachable(nested, {"OUTER": outer, "INNER": " EXIT.\n"}) == ["NEXT-PARA"]+++def test_control_paths_the_text_names_or_runs_into_are_kept() -> None:+ cases = {+ # PERFORM A THRU C runs B by falling out of A.+ "thru_interior": " PERFORM A-PARA THRU C-PARA\n GOBACK.\n"+ " A-PARA.\n MOVE 1 TO X.\n B-PARA.\n EXIT.\n"+ " C-PARA.\n EXIT.\n",+ # PERFORM of a section runs its paragraphs in order.+ "section": " PERFORM S1\n GOBACK.\n S1 SECTION.\n"+ " P1.\n MOVE 1 TO X.\n P2.\n EXIT.\n",+ "lowercase_mention": " perform next-para\n GOBACK.\n"+ " NEXT-PARA.\n EXIT.\n",+ "handle_abend": " EXEC CICS HANDLE ABEND LABEL(NEXT-PARA) END-EXEC\n"+ " GOBACK.\n NEXT-PARA.\n EXIT.\n",+ "handle_condition": " EXEC CICS HANDLE CONDITION ERROR(NEXT-PARA) END-EXEC\n"+ " GOBACK.\n NEXT-PARA.\n EXIT.\n",+ # Out of range, GO TO DEPENDING ON falls through to the next statement.+ "depending_on": " GO TO A-PARA DEPENDING ON IX.\n"+ " NEXT-PARA.\n EXIT.\n A-PARA.\n EXIT.\n",+ "nohandle": " EXEC CICS RETURN NOHANDLE END-EXEC.\n"+ " NEXT-PARA.\n EXIT.\n",+ "resp": " EXEC CICS XCTL PROGRAM('X') RESP(R) END-EXEC.\n"+ " NEXT-PARA.\n EXIT.\n",+ # A scope terminator in area A is no paragraph header.+ "end_verb": " GOBACK.\n END-PERFORM.\n",+ }+ for case, body in cases.items():+ assert "NEXT-PARA" not in _unreachable(body) and "B-PARA" not in _unreachable(body), case+ assert "P2" not in _unreachable(body) and "END-PERFORM" not in _unreachable(body), case+++def test_lowercase_source_is_read_case_blind() -> None:+ body = " goback.\n next-para.\n exit.\n"+ assert _unreachable(body) == ["NEXT-PARA"]+++def test_end_program_is_a_paragraph_name_not_a_scope_terminator() -> None:+ body = (+ " GO TO END-PROGRAM.\n END-PROGRAM.\n"+ " EXEC CICS RETURN END-EXEC.\n MAINLINE-EXIT.\n EXIT.\n"+ )+ assert _unreachable(body) == ["MAINLINE-EXIT"]diff --git a/tests/unit/ingestion/test_mainframe_edges.py b/tests/unit/ingestion/test_mainframe_edges.pyindex b54e49cbe..8cd691792 100644--- a/tests/unit/ingestion/test_mainframe_edges.py+++ b/tests/unit/ingestion/test_mainframe_edges.py@@ -7,6 +7,7 @@ from types import SimpleNamespaceimport networkx as nximport pytest+from repowise.core.ingestion.cobol.csd import defined_programs, read_csdfrom repowise.core.ingestion.cobol.jcl import read_jclfrom repowise.core.ingestion.framework_edges.mainframe import _add_mainframe_edgesfrom repowise.core.ingestion.parser import ASTParser@@ -106,3 +107,193 @@ def test_a_step_never_runs_a_job_as_its_procedure() -> None:_add_mainframe_edges(graph, parsed, ctx)assert set(graph.edges) == {("jcl/RUNNER.jcl", "jcl/LIB.jcl")}+++CSD = b""" DEFINE PROGRAM(COACTUPC) GROUP(CARDDEMO)+ DESCRIPTION(CREDIT CARD DEMO ACCOUNT UPDATE)+ RELOAD(NO) DELETE(YES)+ DEFINE TRANSACTION(CAUP) GROUP(CARDDEMO)+ DESCRIPTION(ACCOUNT UPDATE)+ PROGRAM(COMENU1C) TWASIZE(0) PROFILE(DFHCICST)+* DEFINE PROGRAM(COMMENTED) GROUP(CARDDEMO)+ DEFINE MAPSET(COSGN00) GROUP(CARDDEMO)+"""+CSD_JOB = b"""//GENACSD JOB 241901,'CSD GENERATE',CLASS=A+//CSDDEFS EXEC PGM=DFHCSDUP,REGION=1M+//SYSIN DD *+*Delete Group(GENA) All+Add Group(GENASAT) List(GENALIST)+Define Transaction(SSC1) Group(GENASAT)+ Program(LGTESTC1) TaskDataLoc(Any)+Define Program(LGACUS01) Group(GENASAP)+/*+//NEXT EXEC PGM=IEFBR14+"""+++def _program(name: bytes, procedure: bytes = b" GOBACK.\n") -> bytes:+ return (+ b" IDENTIFICATION DIVISION.\n PROGRAM-ID. " + name + b".\n"+ b" DATA DIVISION.\n WORKING-STORAGE SECTION.\n"+ b" 01 WS-TRANID PIC X(4) VALUE 'CAUP'.\n"+ b" PROCEDURE DIVISION.\n MAIN-PARA.\n" + procedure+ )+++def _edges(files: dict[str, tuple[str, bytes]]) -> nx.DiGraph:+ parser = ASTParser()+ parsed = {+ p: parser.parse_file(_make_file_info(p, lang), src) for p, (lang, src) in files.items()+ }+ graph = nx.DiGraph()+ graph.add_nodes_from(files)+ _add_mainframe_edges(graph, parsed, SimpleNamespace(source_map={p: s for p, (_, s) in files.items()}))+ return graph+++def test_csd_definitions_read_continuations_and_skip_comments() -> None:+ defs = read_csd(enumerate(CSD.decode().splitlines(), 1))+ assert [(d.resource, d.name, d.program) for d in defs] == [+ ("PROGRAM", "COACTUPC", None),+ ("TRANSACTION", "CAUP", "COMENU1C"),+ ("MAPSET", "COSGN00", None),+ ]+ assert defined_programs(defs) == ["COACTUPC", "COMENU1C"]+++def test_csd_definitions_in_jcl_in_stream_data() -> None:+ member = read_jcl(CSD_JOB.decode())+ defs = read_csd(member.in_stream)+ assert [(d.resource, d.name, d.program) for d in defs] == [+ ("TRANSACTION", "SSC1", "LGTESTC1"),+ ("PROGRAM", "LGACUS01", None),+ ]+ assert [s.program for s in member.steps] == ["DFHCSDUP", "IEFBR14"]+++def test_defined_programs_are_roots_linked_from_their_definition() -> None:+ graph = _edges(+ {+ "csd/CARDDEMO.CSD": ("csd", CSD),+ "cntl/cdef121.jcl": ("jcl", CSD_JOB),+ "cbl/COACTUPC.cbl": ("cobol", _program(b"COACTUPC")),+ "cbl/COMENU1C.cbl": ("cobol", _program(b"COMENU1C")),+ "cbl/LGTESTC1.cbl": ("cobol", _program(b"LGTESTC1")),+ "cbl/LGACUS01.cbl": ("cobol", _program(b"LGACUS01")),+ "cbl/UNDEFINED.cbl": ("cobol", _program(b"UNDEFINED")),+ }+ )+ assert set(graph.edges) == {+ ("csd/CARDDEMO.CSD", "cbl/COACTUPC.cbl"),+ ("csd/CARDDEMO.CSD", "cbl/COMENU1C.cbl"),+ ("cntl/cdef121.jcl", "cbl/LGTESTC1.cbl"),+ ("cntl/cdef121.jcl", "cbl/LGACUS01.cbl"),+ }+ roots = {p for p, d in graph.nodes(data=True) if d.get("is_reachability_root")}+ assert roots == {+ "cbl/COACTUPC.cbl",+ "cbl/COMENU1C.cbl",+ "cbl/LGTESTC1.cbl",+ "cbl/LGACUS01.cbl",+ }+++def test_return_and_start_transid_link_to_the_transaction_program() -> None:+ returns = _program(+ b"COSGN00C",+ b" EXEC CICS STARTBR FILE('X') RIDFLD(K) END-EXEC\n"+ b" EXEC CICS START TRANSID('SSC1') END-EXEC\n"+ b" EXEC CICS RETURN TRANSID(WS-TRANID) END-EXEC.\n",+ )+ graph = _edges(+ {+ "csd/CARDDEMO.CSD": ("csd", CSD),+ "cntl/cdef121.jcl": ("jcl", CSD_JOB),+ "cbl/COSGN00C.cbl": ("cobol", returns),+ "cbl/COMENU1C.cbl": ("cobol", _program(b"COMENU1C")),+ "cbl/LGTESTC1.cbl": ("cobol", _program(b"LGTESTC1")),+ }+ )+ assert set(graph.successors("cbl/COSGN00C.cbl")) == {"cbl/COMENU1C.cbl", "cbl/LGTESTC1.cbl"}+++def test_a_transid_is_not_linked_to_its_own_program_or_an_ambiguous_one() -> None:+ other_region = CSD.replace(b"PROGRAM(COMENU1C)", b"PROGRAM(COOTHER)")+ graph = _edges(+ {+ "csd/A.csd": ("csd", CSD),+ "csd/B.csd": ("csd", other_region),+ "cbl/COMENU1C.cbl": (+ "cobol",+ _program(b"COMENU1C", b" EXEC CICS RETURN TRANSID('CAUP') END-EXEC.\n"),+ ),+ "cbl/CALLER.cbl": (+ "cobol",+ _program(b"CALLER", b" EXEC CICS RETURN TRANSID('CAUP') END-EXEC.\n"),+ ),+ "cbl/COOTHER.cbl": ("cobol", _program(b"COOTHER")),+ }+ )+ assert set(graph.successors("cbl/COMENU1C.cbl")) == set()+ assert set(graph.successors("cbl/CALLER.cbl")) == set()+++def test_csd_abbreviations_and_unknown_commands_end_a_definition() -> None:+ text = (+ "DEFINE TRANSACTION(T2) GROUP(G)\n"+ "DEF TRANS(T3) GROUP(G)\n"+ " PROG(P3)\n"+ "FOO BAR(X)\n"+ " PROGRAM(P9)\n"+ "DEFINE PROGRAM(P4) GROUP(G)\n"+ "ALT TRANSACTION(T3) PROGRAM(OTHER)\n"+ "DELETE PROGRAM(P4) GROUP(G)\n"+ )+ defs = read_csd(enumerate(text.splitlines(), 1))+ assert [(d.command, d.resource, d.name, d.program) for d in defs] == [+ ("DEFINE", "TRANSACTION", "T2", None),+ ("DEFINE", "TRANSACTION", "T3", "P3"),+ ("DEFINE", "PROGRAM", "P4", None),+ ("ALTER", "TRANSACTION", "T3", "OTHER"),+ ]+++def test_an_altered_transaction_and_a_runtime_transid_link_nowhere() -> None:+ altered = CSD + b" ALTER TRANSACTION(CAUP) GROUP(CARDDEMO) PROGRAM(COOTHER)\n"+ dynamic = _program(+ b"CALLER",+ b" MOVE WS-INPUT TO WS-TRANID\n"+ b" EXEC CICS RETURN TRANSID(WS-TRANID) END-EXEC.\n",+ )+ literal = _program(b"CALLER2", b" EXEC CICS RETURN TRANSID('CAUP') END-EXEC.\n")+ graph = _edges(+ {+ "csd/CARDDEMO.CSD": ("csd", CSD),+ "cbl/CALLER.cbl": ("cobol", dynamic),+ "cbl/COMENU1C.cbl": ("cobol", _program(b"COMENU1C")),+ }+ )+ assert set(graph.successors("cbl/CALLER.cbl")) == set()+ graph = _edges(+ {+ "csd/CARDDEMO.CSD": ("csd", altered),+ "cbl/CALLER2.cbl": ("cobol", literal),+ "cbl/COMENU1C.cbl": ("cobol", _program(b"COMENU1C")),+ "cbl/COOTHER.cbl": ("cobol", _program(b"COOTHER")),+ }+ )+ assert set(graph.successors("cbl/CALLER2.cbl")) == set()+ assert graph.nodes["cbl/COOTHER.cbl"].get("is_reachability_root") is True+++def test_in_stream_data_ends_at_its_dlm_delimiter() -> None:+ member = read_jcl(+ "//J JOB CLASS=A\n//S1 EXEC PGM=DFHCSDUP\n//SYSIN DD DATA,DLM=@@\n"+ "//NOTJCL looks like a statement\nDEFINE PROGRAM(P1) GROUP(G)\n@@\n"+ "//S2 EXEC PGM=IEFBR14\n"+ )+ assert [line for _, line in member.in_stream] == [+ "//NOTJCL looks like a statement",+ "DEFINE PROGRAM(P1) GROUP(G)",+ ]+ assert [s.program for s in member.steps] == ["DFHCSDUP", "IEFBR14"]