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): index JCL and BMS, linking job steps to programs and programs to mapsets (#4438)

Raghav Chamadiya5297e108c7d1
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 5c7819c0d..0b33caf6c 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -85,7 +85,9 @@ nearest copybook with that name; system copybooks such as `DFHAID` stay external
constant moved into the program variable; any other target shows as a
`cics-dynamic:` reference rather than a guess. A `PERFORM` binds only within
its program and the copybooks it copies; `CALL`, `LINK` and `XCTL` bind to a
-unique PROGRAM-ID.
+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.
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
diff --git a/packages/core/src/repowise/core/ingestion/call_cobol.py b/packages/core/src/repowise/core/ingestion/call_cobol.py
index 2723d883e..afb86c654 100644
--- a/packages/core/src/repowise/core/ingestion/call_cobol.py
+++ b/packages/core/src/repowise/core/ingestion/call_cobol.py
@@ -22,7 +22,7 @@ class CobolCallsMixin:
) -> ResolvedCall | None:
name = call.target_name
if call.program_call:
- return self._cobol_program(name, call, caller_id)
+ return self._cobol_program(file_path, name, call, caller_id)
own = self._cobol_symbol(file_path, name, _PROCEDURE_KINDS)
if own is not None:
return (
@@ -36,14 +36,17 @@ class CobolCallsMixin:
return ResolvedCall(caller_id, hit, 0.90, call.line, "import_scoped")
return None
- def _cobol_program(self, name: str, call: CallSite, caller_id: str) -> ResolvedCall | None:
+ def _cobol_program(
+ self, file_path: str, name: str, call: CallSite, caller_id: str
+ ) -> ResolvedCall | None:
programs = [
sym_id
for sym_id in self._global_symbols.get(name, ()) # type: ignore[attr-defined]
if self._symbols_by_id[sym_id].kind in _PROGRAM_KINDS # type: ignore[attr-defined]
and self._symbols_by_id[sym_id].language == "cobol" # type: ignore[attr-defined]
]
- if len(programs) != 1 or programs[0] == caller_id:
+ # A program naming itself (a bookkeeping constant) is not a transfer.
+ if len(programs) != 1 or self._symbol_paths_by_id.get(programs[0]) == file_path: # type: ignore[attr-defined]
return None
return ResolvedCall(caller_id, programs[0], 0.50, call.line, "global_unique")
diff --git a/packages/core/src/repowise/core/ingestion/cobol/bms.py b/packages/core/src/repowise/core/ingestion/cobol/bms.py
new file mode 100644
index 000000000..f3b596a72
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/cobol/bms.py
@@ -0,0 +1,54 @@
+"""BMS map source: the mapset (``DFHMSD``) and its maps (``DFHMDI``) as symbols."""
+
+from __future__ import annotations
+
+import re
+
+from ..models import FileInfo, ParsedFile, Symbol
+
+# A labelled macro in column 1: ``COSGN00 DFHMSD TYPE=&&SYSPARM,...``.
+_MACRO = re.compile(r"^(?P<label>[A-Z0-9#@$]{1,8})\s+(?P<macro>DFHMSD|DFHMDI)\b", re.I)
+_FINAL = re.compile(r"\bDFHMSD\s+TYPE=FINAL\b", re.I)
+
+
+def parse_bms_file(file_info: FileInfo, source: bytes) -> ParsedFile:
+ lines = source.decode("utf-8", errors="replace").splitlines()
+ end = len(lines)
+ for number, line in enumerate(lines, 1):
+ if _FINAL.search(line):
+ end = number
+ break
+ symbols: list[Symbol] = []
+ for number, line in enumerate(lines[:end], 1):
+ m = _MACRO.match(line)
+ if m is None:
+ continue
+ name, macro = m.group("label").upper(), m.group("macro").upper()
+ kind = "module" if macro == "DFHMSD" else "class"
+ if kind == "class" and symbols and symbols[-1].kind == "class":
+ symbols[-1].end_line = number - 1
+ symbols.append(
+ Symbol(
+ id=f"{file_info.path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind=kind,
+ signature=f"{name} {macro}",
+ start_line=number,
+ end_line=end,
+ docstring=None,
+ language="bms",
+ )
+ )
+ return ParsedFile(
+ file_info=file_info,
+ symbols=symbols,
+ imports=[],
+ exports=[s.name for s in symbols],
+ docstring=None,
+ parse_errors=[],
+ )
+
+
+def mapset_names(parsed: ParsedFile) -> list[str]:
+ return [s.name for s in parsed.symbols if s.kind == "module"]
diff --git a/packages/core/src/repowise/core/ingestion/cobol/cics.py b/packages/core/src/repowise/core/ingestion/cobol/cics.py
index cea1df224..dde485cba 100644
--- a/packages/core/src/repowise/core/ingestion/cobol/cics.py
+++ b/packages/core/src/repowise/core/ingestion/cobol/cics.py
@@ -1,9 +1,9 @@
-"""CICS ``LINK`` / ``XCTL`` program transfers, with in-program constant tracking.
+"""CICS ``LINK`` / ``XCTL`` programs and ``SEND`` / ``RECEIVE MAP`` mapsets, with constant tracking.
``PROGRAM('X')`` names its target. ``PROGRAM(VAR)`` names every value the
program 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
-transfer dynamic, reported as such and never guessed.
+target dynamic, reported as such and never guessed. ``MAPSET`` reads the same way.
Ceiling: only the program's own text is read, so a constant defined in a
copybook, or a value arriving through a group move (a COMMAREA), is dynamic.
@@ -23,7 +23,11 @@ DYNAMIC_PREFIX = "dynamic:"
_NAME = r"[A-Z0-9#@$][A-Z0-9#@$-]*"
_LITERAL = r"'[^']*'|\"[^\"]*\""
_TRANSFER = re.compile(r"^\s*(LINK|XCTL)\b", re.IGNORECASE)
-_PROGRAM = re.compile(rf"\bPROGRAM\s*\(\s*(?:(?P<lit>{_LITERAL})|(?P<var>{_NAME}))\s*\)", re.I)
+_OPERAND = rf"\s*\(\s*(?:(?P<lit>{_LITERAL})|(?P<var>{_NAME}))\s*\)"
+_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)
_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>[^.]*))",
@@ -34,6 +38,10 @@ _VALUE = re.compile(
rf"^\s*\d\d\s+(?P<name>{_NAME})\b[^.]*?\bVALUE\s+(?:IS\s+)?(?P<lit>{_LITERAL})",
re.IGNORECASE | re.MULTILINE,
)
+# A paragraph or section header in area A, alone on its line.
+_PARAGRAPH = re.compile(rf"^ {{7,10}}{_NAME}(?:\s+SECTION)?\s*\.\s*$", re.IGNORECASE | re.MULTILINE)
+_ARM = re.compile(r"(?<![\w-])(?:WHEN|ELSE)(?![\w-])", re.IGNORECASE)
+_SCOPE_END = re.compile(r"(?<![\w-])END-(?:IF|EVALUATE)(?![\w-])", re.IGNORECASE)
_WORD = re.compile(rf"{_NAME}|\([^)]*\)|,|\S+", re.IGNORECASE)
# A MOVE's receiving list ends at the next statement's verb or a scope end.
_VERBS = frozenset(
@@ -78,8 +86,8 @@ _VERBS = frozenset(
@dataclass(frozen=True)
-class ProgramTransfer:
- """One ``EXEC CICS LINK|XCTL``: its static targets, and the variable when dynamic."""
+class CicsTarget:
+ """One CICS command's named program or mapset: static values, and the variable when dynamic."""
verb: str
line: int
@@ -87,46 +95,68 @@ class ProgramTransfer:
dynamic: str | None = None
-def program_transfers(code: str) -> list[ProgramTransfer]:
- """Every LINK/XCTL in *code* (a code view), its targets resolved where static."""
+def program_transfers(code: str) -> list[CicsTarget]:
+ """Every LINK/XCTL in *code* (a code view), its program resolved where static."""
+ return _cics_targets(code, _TRANSFER, _PROGRAM)
+
+
+def mapset_uses(code: str) -> list[CicsTarget]:
+ """Every SEND/RECEIVE MAP in *code*, by its MAPSET (CICS defaults it to the MAP)."""
+ return _cics_targets(code, _MAP_COMMAND, _MAPSET, fallback=_MAP)
+
+
+def _cics_targets(
+ code: str,
+ command: re.Pattern[str],
+ option: re.Pattern[str],
+ fallback: re.Pattern[str] | None = None,
+) -> list[CicsTarget]:
statements = mask_statements(code)
moves = _moves(statements)
other_writes = {m.group(1).upper() for m in _OTHER_WRITE.finditer(statements)}
- rewritten = {name for _, dsts in moves for name in dsts} | other_writes
+ rewritten = {name for _, _, dsts in moves for name in dsts} | other_writes
constants = {
m.group("name").upper(): _unquote(m.group("lit"))
for m in _VALUE.finditer(statements)
if m.group("name").upper() not in rewritten
}
- out: list[ProgramTransfer] = []
+ paragraphs = [m.start() for m in _PARAGRAPH.finditer(statements)]
+ arms = sorted(paragraphs + [m.start() for m in _ARM.finditer(statements)])
+ out: list[CicsTarget] = []
for block in exec_blocks(code):
- verb = _TRANSFER.match(block.body) if block.kind == "CICS" else None
- program = _PROGRAM.search(block.body) if verb else None
- if program is None:
+ verb = command.match(block.body) if block.kind == "CICS" else None
+ operand = option.search(block.body) if verb else None
+ if verb and operand is None and fallback is not None:
+ operand = fallback.search(block.body)
+ if operand is None:
continue
- if program.group("lit"):
- out.append(
- ProgramTransfer(
- verb.group(1).upper(), block.line, (_unquote(program.group("lit")),)
- )
- )
+ name = verb.group(1).upper()
+ if operand.group("lit"):
+ out.append(CicsTarget(name, block.line, (_unquote(operand.group("lit")),)))
continue
- var = program.group("var").upper()
- targets, dynamic = _values_of(var, moves, constants)
+ var = operand.group("var").upper()
+ # The nearest scope (WHEN/ELSE arm, then paragraph) whose last assignment
+ # is unconditional decides; otherwise every assignment in the program does.
+ scoped = moves
+ for bounds in (arms, paragraphs):
+ start = max((p for p in bounds if p < block.start), default=0)
+ local = [m for m in moves if start < m[0] < block.start and var in m[2]]
+ if local and not _SCOPE_END.search(statements, local[-1][0], block.start):
+ scoped = local
+ break
+ targets, dynamic = _values_of(var, scoped, constants)
dynamic = dynamic or var in other_writes
- out.append(
- ProgramTransfer(verb.group(1).upper(), block.line, targets, var if dynamic else None)
- )
+ out.append(CicsTarget(name, block.line, targets, var if dynamic else None))
return out
def _values_of(
- var: str, moves: list[tuple[str, set[str]]], constants: dict[str, str]
+ var: str, moves: list[tuple[int, str, set[str]]], constants: dict[str, str]
) -> tuple[tuple[str, ...], bool]:
- """``(static values, any non-static assignment)`` for *var*."""
+ """``(static values, any non-static assignment)`` for *var* across *moves*."""
values: list[str] = []
dynamic = False
- sources = [src for src, dsts in moves if var in dsts]
+ sources = [src for _, src, dsts in moves if var in dsts]
if not sources:
if var in constants:
return (constants[var],), False
@@ -144,8 +174,8 @@ def _values_of(
return tuple(values), dynamic
-def _moves(code: str) -> list[tuple[str, set[str]]]:
- """``(source, {receivers})`` for each MOVE; a literal source keeps its quotes."""
+def _moves(code: str) -> list[tuple[int, str, set[str]]]:
+ """``(offset, source, {receivers})`` per MOVE; a literal source keeps its quotes."""
out = []
for m in _MOVE.finditer(code):
src = m.group("src")
@@ -162,7 +192,7 @@ def _moves(code: str) -> list[tuple[str, set[str]]]:
qualifier = False
elif re.fullmatch(_NAME, word, re.IGNORECASE):
receivers.add(word)
- out.append((src, receivers))
+ out.append((m.start(), src, receivers))
return out
diff --git a/packages/core/src/repowise/core/ingestion/cobol/jcl.py b/packages/core/src/repowise/core/ingestion/cobol/jcl.py
new file mode 100644
index 000000000..9674f71a7
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/cobol/jcl.py
@@ -0,0 +1,135 @@
+"""JCL jobs and procedures: their steps and the programs and PROCs those run.
+
+Read line by line: ``//*`` comments are skipped and a statement continued on
+the 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.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+from ..models import FileInfo, ParsedFile, Symbol
+
+_NAME = r"[A-Z0-9#@$][A-Z0-9#@$]{0,7}"
+_STATEMENT = re.compile(rf"^//(?P<name>{_NAME})?\s+(?P<op>\S+)\s*(?P<operands>.*)$", re.I)
+_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)
+
+
+@dataclass
+class JclStep:
+ name: str
+ line: int
+ end_line: int
+ program: str | None = None
+ procedure: str | None = None
+
+
+@dataclass
+class JclMember:
+ """A job or procedure member: its JOB/PROC names and its steps."""
+
+ jobs: list[str] = field(default_factory=list)
+ procedures: list[str] = field(default_factory=list)
+ steps: list[JclStep] = field(default_factory=list)
+
+
+def read_jcl(text: str) -> JclMember:
+ member = JclMember()
+ lines = text.splitlines()
+ in_stream = False
+ for number, statement in _statements(lines):
+ if in_stream and not statement.startswith("//"):
+ continue
+ in_stream = False
+ m = _STATEMENT.match(statement)
+ if m is None:
+ continue
+ name, op, operands = (
+ (m.group("name") or "").upper(),
+ m.group("op").upper(),
+ m.group("operands"),
+ )
+ if op == "JOB" and name:
+ member.jobs.append(name)
+ elif op == "PROC" and name:
+ member.procedures.append(name)
+ elif op == "EXEC":
+ if member.steps:
+ member.steps[-1].end_line = number - 1
+ step = JclStep(name or f"STEP{len(member.steps) + 1}", number, len(lines))
+ pgm = _PGM.match(operands)
+ proc = None if pgm else _PROC.match(operands)
+ step.program = pgm.group("name").upper() if pgm else None
+ step.procedure = proc.group("name").upper() if proc else None
+ member.steps.append(step)
+ elif op == "DD" and _IN_STREAM.search(f"DD {operands}"):
+ in_stream = True
+ return member
+
+
+def _statements(lines: list[str]) -> list[tuple[int, str]]:
+ """``(line, statement)`` with continuation lines joined; comments dropped."""
+ out: list[tuple[int, str]] = []
+ pending: tuple[int, str] | None = None
+ for number, raw in enumerate(lines, 1):
+ line = raw[:72].rstrip()
+ if line.startswith("//*"):
+ continue
+ if pending is not None and line.startswith("//") and not line[2:3].strip():
+ pending = (pending[0], pending[1] + line[2:].strip())
+ else:
+ if pending is not None:
+ out.append(pending)
+ pending = (number, line)
+ if not pending[1].rstrip().endswith(","):
+ out.append(pending)
+ pending = None
+ if pending is not None:
+ out.append(pending)
+ return out
+
+
+def parse_jcl_file(file_info: FileInfo, source: bytes) -> ParsedFile:
+ """The JOB or PROC as a module symbol, each step as a function inside it."""
+ text = source.decode("utf-8", errors="replace")
+ member = read_jcl(text)
+ line_count = text.count("\n") + 1
+ path = file_info.path
+ symbols = [
+ _symbol(path, name, "module", f"{kind} {name}", 1, line_count)
+ for kind, names in (("JOB", member.jobs), ("PROC", member.procedures))
+ for name in names
+ ]
+ for step in member.steps:
+ runs = f"PGM={step.program}" if step.program else step.procedure or ""
+ symbols.append(
+ _symbol(
+ path, step.name, "function", f"{step.name} EXEC {runs}", step.line, step.end_line
+ )
+ )
+ return ParsedFile(
+ file_info=file_info,
+ symbols=symbols,
+ imports=[],
+ exports=[s.name for s in symbols],
+ docstring=None,
+ parse_errors=[],
+ )
+
+
+def _symbol(path: str, name: str, kind: str, signature: str, start: int, end: int) -> Symbol:
+ return Symbol(
+ id=f"{path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind=kind, # type: ignore[arg-type]
+ signature=signature,
+ start_line=start,
+ end_line=max(start, end),
+ docstring=None,
+ language="jcl",
+ )
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index 369d8d8d2..2e6c68379 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -41,6 +41,7 @@ from . import (
jakarta,
laravel,
lwc,
+ mainframe,
micronaut,
next_app,
pytest_edges,
@@ -109,6 +110,8 @@ _HANDLERS: list[FrameworkHandler] = [
*aura.HANDLERS,
# Salesforce Visualforce: markup names its Apex controller and bound members.
*visualforce.HANDLERS,
+ # JCL steps to programs and PROCs, COBOL programs to BMS mapsets.
+ *mainframe.HANDLERS,
# Last, so an LWC or Aura handler's own edge to the same file wins.
*salesforce_metadata.HANDLERS,
]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py b/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py
new file mode 100644
index 000000000..0894cca51
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/mainframe.py
@@ -0,0 +1,116 @@
+"""Mainframe edges: JCL steps to programs and PROCs, COBOL programs to BMS mapsets.
+
+* ``EXEC PGM=X`` -> the COBOL program whose PROGRAM-ID is X, marked a
+ reachability 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.
+* ``EXEC CICS SEND|RECEIVE MAP ... MAPSET(M)`` -> the BMS source defining M.
+
+A job member is an entry point. Names fold case; two equally near candidates
+bind neither, and a utility (``IDCAMS``, ``SORT``) the repo does not hold links
+to nothing.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING, Any
+
+from ..cobol import code_view
+from ..cobol.cics import mapset_uses
+from ..cobol.jcl import read_jcl
+from ..resolvers.lwc import nearest
+from .aura import _file_edge
+from .base import DetectionContext, FrameworkHandler, source_text
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers import ResolverContext
+
+_PROC_SUFFIXES = frozenset({".prc", ".proc"})
+
+
+def _by_name(parsed_files: dict[str, Any], language: str, kind: str) -> dict[str, list[str]]:
+ """Upper-cased symbol name -> files declaring it, for *language*'s *kind* symbols."""
+ out: dict[str, list[str]] = {}
+ for path in sorted(parsed_files):
+ parsed = parsed_files[path]
+ if parsed.file_info.language != language:
+ continue
+ for sym in parsed.symbols:
+ if sym.kind == kind:
+ out.setdefault(sym.name.upper(), []).append(path)
+ return out
+
+
+def _proc_files(parsed_files: dict[str, Any]) -> dict[str, list[str]]:
+ """PROC name -> member: the file stem, else a PROC (never a JOB) declared in one file."""
+ out: dict[str, list[str]] = {}
+ declared: dict[str, list[str]] = {}
+ for path in sorted(parsed_files):
+ parsed = parsed_files[path]
+ if parsed.file_info.language != "jcl":
+ continue
+ p = PurePosixPath(path)
+ if p.suffix.lower() in _PROC_SUFFIXES:
+ out.setdefault(p.stem.upper(), []).append(path)
+ for sym in parsed.symbols:
+ if sym.kind == "module" and sym.signature.startswith("PROC "):
+ declared.setdefault(sym.name.upper(), []).append(path)
+ for name, paths in declared.items():
+ if name not in out and len(set(paths)) == 1:
+ out[name] = paths
+ return out
+
+
+def _add_mainframe_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext
+) -> int:
+ source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}
+ programs = _by_name(parsed_files, "cobol", "module")
+ mapsets = _by_name(parsed_files, "bms", "module")
+ procs = _proc_files(parsed_files)
+ count = 0
+ for path in sorted(parsed_files):
+ parsed = parsed_files[path]
+ language = parsed.file_info.language
+ if language == "jcl":
+ member = read_jcl(source_text(path, parsed, source_map))
+ if member.jobs and path in graph:
+ graph.nodes[path]["is_entry_point"] = True
+ for 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())
+ elif step.procedure:
+ target = nearest(procs.get(step.procedure, []), path)
+ if target:
+ count += _file_edge(graph, path, target, set())
+ elif language == "cobol" and mapsets:
+ raw = source_map.get(path) or source_text(path, parsed, source_map).encode()
+ for use in mapset_uses(code_view(raw)):
+ for name in use.targets:
+ target = nearest(mapsets.get(name, []), path)
+ if target:
+ count += _file_edge(graph, path, target, set())
+ return count
+
+
+class _MainframeHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ return any(p.file_info.language in ("jcl", "bms") for p in dctx.parsed_files.values())
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_mainframe_edges(graph, parsed_files, ctx)
+
+
+HANDLERS: list[FrameworkHandler] = [_MainframeHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
index 5f24408cf..359bab91b 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
@@ -15,6 +15,7 @@ from .apex import SPEC as _APEX
from .asciidoc import SPEC as _ASCIIDOC
from .astro import SPEC as _ASTRO
from .aura import SPEC as _AURA
+from .bms import SPEC as _BMS
from .c import SPEC as _C
from .clojure import SPEC as _CLOJURE
from .cobol import SPEC as _COBOL
@@ -36,6 +37,7 @@ from .haskell import SPEC as _HASKELL
from .html import SPEC as _HTML
from .java import SPEC as _JAVA
from .javascript import SPEC as _JAVASCRIPT
+from .jcl import SPEC as _JCL
from .json import SPEC as _JSON
from .julia import SPEC as _JULIA
from .kotlin import SPEC as _KOTLIN
@@ -158,6 +160,9 @@ 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.
+ _JCL,
+ _BMS,
# -----------------------------------------------------------------
# Extra languages — git blame coverage only (passthrough + is_code)
# These exist so git_indexer tracks their history even though
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/bms.py b/packages/core/src/repowise/core/ingestion/languages/specs/bms.py
new file mode 100644
index 000000000..de6bcf159
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/bms.py
@@ -0,0 +1,16 @@
+"""LanguageSpec for CICS BMS map source: mapsets and maps as symbols.
+
+``framework_edges/mainframe.py`` links the COBOL programs that send or receive
+a map to its mapset. ``is_code=False``, as for other screen definitions.
+"""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="bms",
+ display_name="BMS",
+ extensions=frozenset({".bms"}),
+ is_code=False,
+ is_passthrough=True,
+ color_hex="#4A7AA8",
+)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/jcl.py b/packages/core/src/repowise/core/ingestion/languages/specs/jcl.py
new file mode 100644
index 000000000..f5e38515a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/jcl.py
@@ -0,0 +1,17 @@
+"""LanguageSpec for JCL jobs and procedures, a symbol-and-edge-only tag.
+
+Steps become symbols in ``cobol/jcl.py``; ``framework_edges/mainframe.py`` links
+each step to the program or PROC it runs. ``is_code=False``: health and dead
+code do not grade job control.
+"""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="jcl",
+ display_name="JCL",
+ extensions=frozenset({".jcl", ".prc", ".proc"}),
+ is_code=False,
+ is_passthrough=True,
+ color_hex="#5C6E8A",
+)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 46c52efe9..330468b86 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -96,6 +96,8 @@ LanguageTag = Literal[
# Salesforce object and field metadata, and saved SOQL queries.
"salesforce_object",
"soql",
+ "jcl",
+ "bms",
"unknown",
]
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cobol.py b/packages/core/src/repowise/core/ingestion/resolvers/cobol.py
index 2bf2d527a..e85dfb3cd 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/cobol.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/cobol.py
@@ -2,8 +2,9 @@
A member resolves case-insensitively to a COBOL file with that stem, a
copybook extension first, then one under the named library, then the one
-nearest the copying file. An unresolved member (``DFHAID``, a vendor or
-system copybook) becomes an external node, never a guess.
+nearest the copying file. With no copybook, a lone BMS mapset of that name
+(the source of a generated symbolic map) answers. An unresolved member
+(``DFHAID``, a vendor or system copybook) becomes an external node, never a guess.
"""
from __future__ import annotations
@@ -33,7 +34,9 @@ def resolve_cobol_import(module_path: str, importer_path: str, ctx: ResolverCont
if posixpath.splitext(path)[1].lower() in extensions and path != importer_path
]
if not candidates:
- return ctx.add_external_node(f"copybook:{member}")
+ # A symbolic map copybook is generated from the BMS mapset of that name.
+ maps = [p for p in ctx.stem_map.get(member.lower(), ()) if p.lower().endswith(".bms")]
+ return maps[0] if len(maps) == 1 else ctx.add_external_node(f"copybook:{member}")
importer_dir = posixpath.dirname(importer_path).split("/")
order = {path: index for index, path in enumerate(candidates)}
diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.py
index d554ca0c5..a7fcd24b6 100644
--- a/packages/core/src/repowise/core/ingestion/special_handlers.py
+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py
@@ -17,6 +17,8 @@ from pathlib import Path
import structlog
+from .cobol.bms import parse_bms_file
+from .cobol.jcl import parse_jcl_file
from .models import FileInfo, Import, ParsedFile, Symbol
from .salesforce_flow import parse_flow_file
from .salesforce_schema import parse_object_metadata
@@ -28,7 +30,17 @@ log = structlog.get_logger(__name__)
# Language tags routed to parse_special by the parser. Kept here, next to
# the handler table, so the two can't drift apart.
SPECIAL_HANDLER_LANGUAGES = frozenset(
- {"openapi", "dockerfile", "makefile", "sql", "salesforce_flow", "salesforce_object", "soql"}
+ {
+ "openapi",
+ "dockerfile",
+ "makefile",
+ "sql",
+ "salesforce_flow",
+ "salesforce_object",
+ "soql",
+ "jcl",
+ "bms",
+ }
)
@@ -47,6 +59,8 @@ def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:
"salesforce_flow": parse_flow_file,
"salesforce_object": parse_object_metadata,
"soql": parse_soql_file,
+ "jcl": parse_jcl_file,
+ "bms": parse_bms_file,
}.get(lang, _parse_unknown)
try:
return handler(file_info, source)
diff --git a/scripts/cobol_acceptance.py b/scripts/cobol_acceptance.py
index 6da816384..516b03d46 100644
--- a/scripts/cobol_acceptance.py
+++ b/scripts/cobol_acceptance.py
@@ -24,7 +24,7 @@ _COPYBOOK_EXTS = {".cpy"}
_JCL_EXTS = {".jcl", ".prc", ".proc"}
_BMS_EXTS = {".bms"}
_NOT_A_PARAGRAPH = {"UNTIL", "VARYING", "WITH", "TEST", "FOREVER", "THRU", "THROUGH"}
-_STRUCTURAL = ("calls", "imports")
+_STRUCTURAL = ("calls", "imports", "framework")
def _walk(root: str) -> dict[str, dict[str, list[str]]]:
diff --git a/tests/unit/ingestion/parser/test_cobol.py b/tests/unit/ingestion/parser/test_cobol.py
index 5f6b26cbc..2c3b89187 100644
--- a/tests/unit/ingestion/parser/test_cobol.py
+++ b/tests/unit/ingestion/parser/test_cobol.py
@@ -222,3 +222,12 @@ class TestCobolCallScope:
GOBACK.
"""
assert self._resolve(parser, {"a.cbl": caller, "b.cbl": callee}, {}) == set()
+
+ def test_a_program_naming_itself_is_not_a_transfer(self, parser: ASTParser) -> None:
+ caller = b""" IDENTIFICATION DIVISION.
+ PROGRAM-ID. COCRDLIC.
+ PROCEDURE DIVISION.
+ MAIN-PARA.
+ EXEC CICS XCTL PROGRAM('COCRDLIC') END-EXEC.
+"""
+ assert self._resolve(parser, {"cocrdlic.cbl": caller}, {}) == set()
diff --git a/tests/unit/ingestion/test_cobol_cics.py b/tests/unit/ingestion/test_cobol_cics.py
index 070d431fc..1e0265126 100644
--- a/tests/unit/ingestion/test_cobol_cics.py
+++ b/tests/unit/ingestion/test_cobol_cics.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from repowise.core.ingestion.cobol import code_view
-from repowise.core.ingestion.cobol.cics import ProgramTransfer, program_transfers
+from repowise.core.ingestion.cobol.cics import CicsTarget, program_transfers
from repowise.core.ingestion.cobol.facts import cobol_imports
@@ -20,14 +20,14 @@ def _program(data: str, procedure: str) -> bytes:
).encode()
-def _transfers(source: bytes) -> list[ProgramTransfer]:
+def _transfers(source: bytes) -> list[CicsTarget]:
return program_transfers(code_view(source))
def test_a_literal_program_is_its_target() -> None:
source = _program("", " EXEC CICS XCTL PROGRAM('COMEN01C') END-EXEC.")
- assert _transfers(source) == [ProgramTransfer("XCTL", 8, ("COMEN01C",))]
+ assert _transfers(source) == [CicsTarget("XCTL", 8, ("COMEN01C",))]
def test_literal_moves_into_the_variable_are_its_targets() -> None:
@@ -40,7 +40,7 @@ def test_literal_moves_into_the_variable_are_its_targets() -> None:
" END-EXEC.",
)
- assert _transfers(source) == [ProgramTransfer("XCTL", 10, ("COADM01C", "COMEN01C"))]
+ assert _transfers(source) == [CicsTarget("XCTL", 10, ("COADM01C", "COMEN01C"))]
def test_a_constant_moved_into_the_variable_is_followed() -> None:
@@ -50,7 +50,7 @@ def test_a_constant_moved_into_the_variable_is_followed() -> None:
" EXEC CICS LINK PROGRAM(CDEMO-TO-PROGRAM) END-EXEC.",
)
- assert _transfers(source) == [ProgramTransfer("LINK", 10, ("COMEN01C",))]
+ assert _transfers(source) == [CicsTarget("LINK", 10, ("COMEN01C",))]
def test_a_variable_assigned_from_another_variable_is_dynamic() -> None:
@@ -62,7 +62,7 @@ def test_a_variable_assigned_from_another_variable_is_dynamic() -> None:
)
assert _transfers(source) == [
- ProgramTransfer("XCTL", 10, ("COSGN00C",), dynamic="CDEMO-TO-PROGRAM")
+ CicsTarget("XCTL", 10, ("COSGN00C",), dynamic="CDEMO-TO-PROGRAM")
]
dynamic = [i.module_path for i in cobol_imports(source) if i.module_path.startswith("dyn")]
assert dynamic == ["dynamic:CDEMO-TO-PROGRAM"]
@@ -74,7 +74,7 @@ def test_a_reassigned_value_is_not_a_constant() -> None:
" MOVE INPUT-PGM TO WS-PGM\n EXEC CICS XCTL PROGRAM(WS-PGM) END-EXEC.",
)
- assert _transfers(source) == [ProgramTransfer("XCTL", 9, (), dynamic="WS-PGM")]
+ assert _transfers(source) == [CicsTarget("XCTL", 9, (), dynamic="WS-PGM")]
def test_a_literal_later_overwritten_by_another_verb_is_dynamic() -> None:
@@ -85,7 +85,7 @@ def test_a_literal_later_overwritten_by_another_verb_is_dynamic() -> None:
" EXEC CICS XCTL PROGRAM(WS-PGM) END-EXEC.",
)
- assert _transfers(source) == [ProgramTransfer("XCTL", 10, ("COMEN01C",), dynamic="WS-PGM")]
+ assert _transfers(source) == [CicsTarget("XCTL", 10, ("COMEN01C",), dynamic="WS-PGM")]
def test_other_cics_commands_and_comments_are_not_transfers() -> None:
@@ -97,3 +97,20 @@ def test_other_cics_commands_and_comments_are_not_transfers() -> None:
)
assert _transfers(source) == []
+
+
+def test_each_when_arm_transfers_to_the_program_it_moves() -> None:
+ source = _program(
+ " 01 NEXT-PROG PIC X(8).",
+ " MOVE 'COCRDLIC' TO NEXT-PROG\n"
+ " EVALUATE TRUE\n"
+ " WHEN WS-VIEW\n"
+ " MOVE 'COCRDSLC' TO NEXT-PROG\n"
+ " EXEC CICS XCTL PROGRAM(NEXT-PROG) END-EXEC\n"
+ " WHEN WS-EDIT\n"
+ " MOVE 'COCRDUPC' TO NEXT-PROG\n"
+ " EXEC CICS XCTL PROGRAM(NEXT-PROG) END-EXEC\n"
+ " END-EVALUATE.",
+ )
+
+ assert [t.targets for t in _transfers(source)] == [("COCRDSLC",), ("COCRDUPC",)]
diff --git a/tests/unit/ingestion/test_mainframe_edges.py b/tests/unit/ingestion/test_mainframe_edges.py
new file mode 100644
index 000000000..b54e49cbe
--- /dev/null
+++ b/tests/unit/ingestion/test_mainframe_edges.py
@@ -0,0 +1,108 @@
+"""JCL and BMS: steps run programs and PROCs, programs send mapsets."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import networkx as nx
+import pytest
+
+from repowise.core.ingestion.cobol.jcl import read_jcl
+from repowise.core.ingestion.framework_edges.mainframe import _add_mainframe_edges
+from repowise.core.ingestion.parser import ASTParser
+
+from .parser._helpers import _make_file_info
+
+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)
+
+JOB = b"""//POSTTRAN JOB 'POSTTRAN',CLASS=A,
+// NOTIFY=&SYSUID
+//* EXEC PGM=COMMENTED
+//STEP05 EXEC PROC=REPROC
+//STEP10 EXEC PGM=CBTRN02C
+//SYSIN DD *
+ EXEC PGM=INSTREAM
+/*
+//STEP20 EXEC PGM=IDCAMS
+"""
+PROC = b"""//REPROC PROC
+//PRC001 EXEC PGM=IDCAMS
+"""
+PROGRAM = b""" IDENTIFICATION DIVISION.
+ PROGRAM-ID. CBTRN02C.
+ PROCEDURE DIVISION.
+ MAIN-PARA.
+ EXEC CICS SEND MAP('COSGN0A') MAPSET('COSGN00') END-EXEC.
+ GOBACK.
+"""
+MAPSET = b"""* LOGIN SCREEN
+COSGN00 DFHMSD TYPE=&&SYSPARM,LANG=COBOL
+COSGN0A DFHMDI SIZE=(24,80)
+ DFHMDF POS=(1,1),LENGTH=10
+ DFHMSD TYPE=FINAL
+"""
+
+
+def test_steps_name_their_program_or_procedure() -> None:
+ member = read_jcl(JOB.decode())
+
+ assert member.jobs == ["POSTTRAN"]
+ assert [(s.name, s.program, s.procedure) for s in member.steps] == [
+ ("STEP05", None, "REPROC"),
+ ("STEP10", "CBTRN02C", None),
+ ("STEP20", "IDCAMS", None),
+ ]
+
+
+def test_jobs_link_programs_and_procs_and_programs_link_mapsets() -> None:
+ files = {
+ "jcl/POSTTRAN.jcl": ("jcl", JOB),
+ "proc/REPROC.prc": ("jcl", PROC),
+ "cbl/CBTRN02C.cbl": ("cobol", PROGRAM),
+ "bms/COSGN00.bms": ("bms", MAPSET),
+ }
+ 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)
+ ctx = SimpleNamespace(source_map={p: src for p, (_, src) in files.items()})
+
+ _add_mainframe_edges(graph, parsed, ctx)
+
+ assert set(graph.edges) == {
+ ("jcl/POSTTRAN.jcl", "proc/REPROC.prc"),
+ ("jcl/POSTTRAN.jcl", "cbl/CBTRN02C.cbl"),
+ ("cbl/CBTRN02C.cbl", "bms/COSGN00.bms"),
+ }
+ assert graph.nodes["jcl/POSTTRAN.jcl"].get("is_entry_point") is True
+ assert graph.nodes["cbl/CBTRN02C.cbl"].get("is_reachability_root") is True
+ assert not graph.nodes["proc/REPROC.prc"].get("is_entry_point")
+ assert {(s.name, s.kind) for s in parsed["bms/COSGN00.bms"].symbols} == {
+ ("COSGN00", "module"),
+ ("COSGN0A", "class"),
+ }
+
+
+def test_a_step_never_runs_a_job_as_its_procedure() -> None:
+ files = {
+ "jcl/RUNNER.jcl": ("jcl", b"//RUNNER JOB CLASS=A\n//S1 EXEC BATCH1\n//S2 EXEC NIGHTLY\n"),
+ "jcl/BATCH1.jcl": ("jcl", b"//BATCH1 JOB CLASS=A\n//S1 EXEC PGM=IEFBR14\n"),
+ "jcl/LIB.jcl": ("jcl", b"//NIGHTLY PROC\n//S1 EXEC PGM=IEFBR14\n"),
+ }
+ 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)
+ ctx = SimpleNamespace(source_map={p: src for p, (_, src) in files.items()})
+
+ _add_mainframe_edges(graph, parsed, ctx)
+
+ assert set(graph.edges) == {("jcl/RUNNER.jcl", "jcl/LIB.jcl")}