Files
cobol-java-v3/cobol_testgen/flatfile.py
T
NB-076 e5ab3baa46 提升:37/37基准程序全量解析+O(N)路径枚举+运行时gcov验证
## 核心变更

### 1. 新PROCEDURE DIVISION解析器(procedure_parser.py)
- 行级状态机替换旧的BrParser regex解析器
- 覆盖:IF/ELSE/END-IF(嵌套)、EVALUATE/WHEN/ALSO、
  PERFORM UNTIL/VARYING、READ/AT END/NOT AT END、
  SORT/MERGE、GO TO DEPENDING ON
- 之前:3/37程序有分支检测  →  现在:37/37全部有分支
- 速度:~20ms/程序,纯规则引擎

### 2. 桥接层(pipeline_bridge.py)
- 新解析器为主,旧解析器3秒超时兜底
- 自动选取分支数更多的结果

### 3. 线性路径枚举(design_mcdc.py)
- 替换旧的Cartesian积路径枚举(O(2^N))为每决策点独立枚举(O(N))
- 28-sysin: 162分支仅163条路径(之前需截断到60DP)
- 消除了500路径硬上限和60DP截断

### 4. 条件解析修复(cond.py)
- NOT运算符规范化:X NOT = 5 → X <> 5
- 88-level反向:NOT WS-EOF-Y → parent <> value
- 裸字段引用:NOT WS-EOF → WS-EOF <> 'Y'
- 验证:1182个IF条件中0个NOT污染

### 5. 约束字段过滤(__init__.py)
- OF限定词剥离:STD-KEY OF MASTER-REC → STD-KEY
- 下标字段解析:WS-ITEM(SUB) → WS-ITEM
- 跳过不在fields_dict中的字段(group item/伪影)

### 6. 预处理器增强(read.py)
- VALUE ALL剥离(VALUE ALL '*' → VALUE '*')
- &续行合并(COBOL多行字符串拼接)
- PIC小数点点→V转换(Z(9)9.99. → Z(9)9V99.)
- 缺少点号补全

### 7. Grammar修复(grammar.lark)
- OCCURS 1 TIME支持(原只认TIMES)
- USAGE IS COMP支持(可选IS)
- $符号在PICTURE_STRING中
- 无NAME条款支持(clause+)

### 8. Flatfile写入(flatfile.py)
- 多记录FD支持(选字段最多的记录)
- Path类型强制转换
- 回退零值记录

### 9. Bug修复
- trace_to_root空列表保护(core.py)

### 10. 测试套件(S16-S21)
- S16: 全量基准程序端到端
- S17: gcov运行时对比
- S18/S19: 桥接器验证
- S20: DISPLAY插桩运行时验证+gcov分支覆盖率
- S21: 条件解析修复验证
- 全部17/17回归测试通过

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-22 23:41:22 +08:00

155 lines
5.7 KiB
Python

"""Flat file I/O — write fixed-length records from COBOL FD definitions"""
import re, struct
from pathlib import Path
from typing import Any
def analyze_fd_layout(source_text: str) -> dict[str, dict]:
"""From preprocessed COBOL source, extract FD file layouts."""
from .read import parse_file_control, parse_file_section, parse_data_division, extract_data_division, scan_open_statements
fc = parse_file_control(source_text) if source_text else {}
fs = parse_file_section(source_text) if source_text else {}
ops = scan_open_statements(source_text) if source_text else {}
dd = extract_data_division(source_text)
all_fields = parse_data_division(dd) if dd else []
layouts = {}
for fd_name, rec_names in fs.items():
records = []
for rec_name in rec_names:
children = []
found = False
rec_level = None
offset = 0
for f in all_fields:
if f.name == rec_name:
found = True
rec_level = f.level
continue
if found:
if f.level is not None and f.level <= rec_level:
break
if f.is_88 or f.is_filler:
continue
pi = f.pic_info
if pi:
length = (pi.digits + pi.decimal) if pi.type == "numeric" else (pi.length or 0)
else:
length = 0
ftype = pi.type if pi else "unknown"
children.append({
"name": f.name, "pic": str(f.pic or ""),
"type": ftype, "length": length, "offset": offset,
})
offset += length
records.append({"record_name": rec_name, "fields": children, "record_length": offset})
assign_to = fc.get(fd_name, {}).get("assign_to", fd_name)
layouts[assign_to] = {
"fd_name": fd_name, "records": records,
"direction": ops.get(fd_name, "INPUT"),
}
return layouts
def select_records_for_file(records: list[dict], layout: dict) -> list[dict]:
"""Extract and route only the fields belonging to this file layout."""
if not layout or not layout.get("records"):
return records
field_names = set()
for rec in layout["records"]:
for f in rec["fields"]:
field_names.add(f["name"])
result = []
for rec in records:
row = {k: v for k, v in rec.items() if k in field_names}
if row:
result.append(row)
return result if result else records
def _format_value(value: Any, field: dict) -> bytes:
"""Format a value for COBOL fixed-length storage."""
ftype = field["type"]
length = field["length"]
val = str(value) if value is not None else ""
if ftype == "numeric":
try:
num = int(float(val)) if val else 0
except (ValueError, TypeError):
num = 0
num = abs(num)
# Truncate to fit PIC digits
max_val = 10 ** length - 1
if num > max_val:
num = max_val
s = str(num).zfill(length)
if len(s) > length:
s = s[-length:]
return s.encode("ascii")
else:
s = val.ljust(length)[:length]
return s.encode("ascii", errors="replace")
def write_flat_file(records: list[dict], layout: dict, outpath: Path, field_filter: set = None):
"""Write records as a COBOL-compatible fixed-length flat file.
Supports multi-record FDs: uses the longest record layout (most fields)
to maximize compatible field coverage.
"""
outpath = Path(outpath)
if not layout or not layout.get("records"):
return
# Pick the record with the most fields (best coverage for multi-record FDs)
rec = max(layout["records"], key=lambda r: (len(r["fields"]), r["record_length"]))
rec_len = rec["record_length"]
if rec_len == 0:
return
rec_fields = rec["fields"]
if field_filter:
rec_fields = [f for f in rec_fields if f["name"] in field_filter]
with open(outpath, "wb") as f:
for row in records:
buf = bytearray(rec_len)
for field in rec_fields:
val = row.get(field["name"], "")
formatted = _format_value(val, field)
end = min(field["offset"] + len(formatted), rec_len)
buf[field["offset"]:end] = formatted[:end - field["offset"]]
f.write(buf)
def write_all_files(records: list[dict], source_text: str, outdir: Path, prefix: str = ""):
"""Analyze source, write flat files for all INPUT FDs."""
outdir = Path(outdir)
layouts = analyze_fd_layout(source_text)
written = []
for filename, layout in layouts.items():
if layout["direction"] == "OUTPUT":
continue
fnames = set()
for rec in layout["records"]:
for f in rec["fields"]:
fnames.add(f["name"])
if not fnames:
continue
# Filter generated records to only include fields from this FD
filtered = [{k: v for k, v in r.items() if k in fnames} for r in records]
has_data = any(v for row in filtered for v in row.values())
if not has_data:
# Fallback: one zero-filled record from FD layout
fallback = {}
for rec in layout["records"]:
for f in rec["fields"]:
fallback[f["name"]] = 0 if f["type"] == "numeric" else " "
filtered = [fallback] if fallback else []
if filtered:
outpath = outdir / (prefix + filename)
write_flat_file(filtered, layout, outpath)
written.append((filename, outpath, len(filtered)))
return written