407 lines
20 KiB
Python
407 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Inventory every public AIR rejection and verify audited source twins.
|
|
|
|
Pending, source-error analogues and AIR-only cases remain unmet P6-7 rows.
|
|
Default: verify declared pairs and report incomplete coverage. --inventory:
|
|
JSON inventory without running the compiler. --require-complete: also fail
|
|
unless every AIR rejection has a verified same-code source twin.
|
|
"""
|
|
import argparse
|
|
from collections import Counter
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CORPUS = ROOT / 'tests/conformance'
|
|
MANIFEST = CORPUS / 'reject-twins.json'
|
|
IDENTITIES = {'function', 'block', 'inst', 'borrow', 'resource', 'task',
|
|
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from'}
|
|
ENVELOPE = {'code', 'kind', 'severity', 'file', 'line', 'col', 'air_line',
|
|
'air_col', 'message', 'related_locations'}
|
|
|
|
|
|
def unique(pairs):
|
|
out = {}
|
|
for key, value in pairs:
|
|
if key in out:
|
|
raise ValueError(f'duplicate JSON member: {key}')
|
|
out[key] = value
|
|
return out
|
|
|
|
|
|
def load_json(text):
|
|
return json.loads(text, object_pairs_hook=unique)
|
|
|
|
|
|
def codes(path):
|
|
prefix = ';' if path.suffix == '.air' else '//'
|
|
found = re.findall(r'^' + re.escape(prefix) + r' expect: reject (.+)$',
|
|
path.read_text(), re.MULTILINE)
|
|
if not found:
|
|
return None
|
|
if len(found) != 1:
|
|
raise ValueError(f'{path}: duplicate rejection header')
|
|
return found[0].split()
|
|
|
|
|
|
def corpus_path(name, suffix):
|
|
p = (CORPUS / name).resolve()
|
|
if not p.is_relative_to(CORPUS.resolve()) or p.suffix != suffix or not p.is_file():
|
|
raise ValueError(f'invalid corpus path: {name}')
|
|
return p
|
|
|
|
|
|
def inventory():
|
|
manifest = load_json(MANIFEST.read_text())
|
|
if manifest['version'] != 1:
|
|
raise ValueError('unsupported rejection-twin manifest version')
|
|
air = {str(p.relative_to(CORPUS)): codes(p) for p in sorted(CORPUS.rglob('*.air')) if codes(p)}
|
|
declared = {}
|
|
for p in sorted(CORPUS.rglob('*.aji')):
|
|
links = re.findall(r'^// AIR twin: (.+)$', p.read_text(), re.MULTILINE)
|
|
if len(links) != len(set(links)):
|
|
raise ValueError(f'{p}: duplicate AIR twin link')
|
|
for target in links:
|
|
corpus_path(target, '.air')
|
|
if target not in air or not codes(p):
|
|
raise ValueError(f'{p}: twin must name an AIR rejection and reject itself')
|
|
if Counter(air[target]) != Counter(codes(p)):
|
|
raise ValueError(f'{p}: declared source/AIR rejection codes differ')
|
|
declared.setdefault(target, []).append(str(p.relative_to(CORPUS)))
|
|
unknown = set(manifest['cases']) - set(air)
|
|
if unknown:
|
|
raise ValueError(f'manifest has missing/non-reject AIR cases: {sorted(unknown)}')
|
|
rows = []
|
|
for name, expected in air.items():
|
|
review = manifest['cases'].get(name)
|
|
sources = declared.get(name, [])
|
|
if sources and (review is None or review['kind'] != 'same_code'):
|
|
raise ValueError(f'{name}: declared twin lacks a same-code rule audit')
|
|
if review is None:
|
|
row = {'air': name, 'codes': expected, 'kind': 'pending', 'sources': []}
|
|
else:
|
|
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues', 'required_ops'}
|
|
if set(review) - allowed:
|
|
raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}')
|
|
witnesses = review.get('required_ops', {})
|
|
if not isinstance(witnesses, dict) or any(
|
|
not isinstance(op, str) or not op or
|
|
not isinstance(n, int) or isinstance(n, bool) or n < 1
|
|
for op, n in witnesses.items()):
|
|
raise ValueError(f'{name}: operation witness counts must be positive integers')
|
|
if review.get('lowering') not in {None, 'rejected'}:
|
|
raise ValueError(f'{name}: invalid lowering mode')
|
|
if review['kind'] not in {'same_code', 'source_error', 'air_only'}:
|
|
raise ValueError(f'{name}: invalid classification')
|
|
if not review.get('rule') or not review.get('spec'):
|
|
raise ValueError(f'{name}: missing rule/spec evidence')
|
|
spec = (ROOT / review['spec'].split(' §')[0]).resolve()
|
|
if not spec.is_relative_to((ROOT / 'docs/spec').resolve()) or not spec.is_file():
|
|
raise ValueError(f'{name}: invalid governing spec')
|
|
if review['kind'] == 'same_code':
|
|
if not sources or review.get('site') not in {'instruction', 'block', 'function', 'declaration'}:
|
|
raise ValueError(f'{name}: missing source/site')
|
|
elif sources:
|
|
raise ValueError(f'{name}: analogue/inexpressible case cannot count as a twin')
|
|
if review['kind'] == 'source_error' and not review.get('analogues'):
|
|
raise ValueError(f'{name}: source-error classification needs an analogue')
|
|
for analogue in review.get('analogues', []):
|
|
if not analogue.get('codes') or any(not re.fullmatch(r'E7[0-9]{3}', c) for c in analogue['codes']):
|
|
raise ValueError(f'{name}: source-error analogue must use E7xxx')
|
|
p = corpus_path(analogue['source'], '.aji')
|
|
if Counter(codes(p) or []) != Counter(analogue['codes']):
|
|
raise ValueError(f'{name}: analogue header does not match')
|
|
row = {'air': name, 'codes': expected, 'sources': sources, **review}
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def command(aji, *args, status):
|
|
p = subprocess.run([str(aji), *map(str, args)], capture_output=True, text=True)
|
|
if p.returncode != status:
|
|
raise ValueError(f'{args}: expected exit {status}, got {p.returncode}: {p.stdout} {p.stderr}')
|
|
return p.stdout
|
|
|
|
|
|
def errors(aji, path):
|
|
ds = [load_json(line) for line in command(aji, 'check', path, status=1).splitlines()]
|
|
if not ds or any(d.get('severity') != 'error' for d in ds):
|
|
raise ValueError(f'{path}: expected error records only')
|
|
if Counter(d['code'] for d in ds) != Counter(codes(path) or []):
|
|
raise ValueError(f'{path}: diagnostics do not match rejection header')
|
|
return ds
|
|
|
|
|
|
def payload(d):
|
|
# Compare stable rule facts independently of spelling, prose and locations.
|
|
return {k: v for k, v in d.items() if k not in ENVELOPE | IDENTITIES}
|
|
|
|
|
|
def operation(line):
|
|
line = line.strip()
|
|
if '=' in line and line.startswith('%'):
|
|
line = line.split('=', 1)[1].strip()
|
|
op = line.split()[0]
|
|
if op == 'intrinsic':
|
|
op += ' ' + line.split()[1].split('(', 1)[0]
|
|
return op
|
|
|
|
|
|
def site_key(source, d, site):
|
|
lines = source.splitlines()
|
|
if not (1 <= d['line'] <= len(lines)) or d['col'] < 1:
|
|
raise ValueError('diagnostic coordinates outside AIR')
|
|
line = lines[d['line'] - 1].strip()
|
|
if site == 'instruction':
|
|
if line.endswith(':') or line.startswith(('fn ', 'type ', ';')):
|
|
raise ValueError(f'expected instruction, got {line}')
|
|
return operation(line)
|
|
if site == 'block':
|
|
if not line.endswith(':'):
|
|
raise ValueError(f'expected block label, got {line}')
|
|
return 'block'
|
|
if site == 'function':
|
|
if not line.startswith('fn '):
|
|
raise ValueError(f'expected function declaration, got {line}')
|
|
return 'function'
|
|
if not line.startswith('type '):
|
|
raise ValueError(f'expected type declaration, got {line}')
|
|
return 'declaration'
|
|
|
|
|
|
def identity_class(air, d, value):
|
|
"""Root constructor/producer class, not a second AIR type checker.
|
|
|
|
This also intentionally merges the same exclusive-alias rule against
|
|
shared or exclusive borrows. Content types do not distinguish the same
|
|
whole-resource/loan rule:
|
|
own<u8>/own<u64> are owners, and ref/slice forms are borrows. Resource
|
|
families (region/frozen/own/file<read>/...) must remain distinct.
|
|
Unsupported producers fail closed and need a reviewed extension.
|
|
"""
|
|
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL)
|
|
if not function or not isinstance(value, str) or not value.startswith('%'):
|
|
raise ValueError('identity has no defining function/value')
|
|
text = function[0]
|
|
for line in text.splitlines():
|
|
line = line.split(';', 1)[0].strip()
|
|
if not (line.startswith('fn @') or re.fullmatch(r'[^\s(]+\(.*\):', line)):
|
|
continue
|
|
typed = re.search(re.escape(value) + r':\s*([@A-Za-z_][\w.]*)(<[^\s,)]*>)?', line)
|
|
if typed:
|
|
root, suffix = typed.groups()
|
|
if root in {'ref', 'mut', 'slice', 'slice_mut'}:
|
|
return 'borrow'
|
|
return root + (suffix or '') if root in {'file', 'cap'} else root
|
|
producers = {'local.alloc': 'local', 'atomic.new': 'atomic', 'mutex.make': 'mutex',
|
|
'island.freeze': 'frozen', 'arc.from_frozen': 'arc', 'arc.clone': 'arc',
|
|
'task.spawn': 'task', 'task.scope.begin': 'scope', 'task.shield.begin': 'shield'}
|
|
for line in text.splitlines():
|
|
definition = re.match(r'\s*(%[^=]+?)\s*=\s*([\w.]+)', line)
|
|
if definition and value in [x.strip() for x in definition[1].split(',')]:
|
|
op = definition[2]
|
|
if op.startswith('borrow.') or op in {'slice.make', 'slice.sub', 'slice.split', 'buffer.view'}:
|
|
return 'borrow'
|
|
if op in producers:
|
|
return producers[op]
|
|
raise ValueError(f'unsupported identity producer: {op}')
|
|
raise ValueError(f'identity has no audited definition: {value}')
|
|
|
|
|
|
def positions(source):
|
|
marked = []
|
|
for line_no, line in enumerate(source.splitlines(), 1):
|
|
match = re.fullmatch(r'(.+?)\s+// diagnostic here(?:: (.+))?', line)
|
|
if not match or match[1].lstrip().startswith('//'):
|
|
continue
|
|
code, token = match.groups()
|
|
if token:
|
|
matches = [m.start() for m in re.finditer(re.escape(token), code)]
|
|
if len(matches) != 1:
|
|
raise ValueError('position marker must identify a unique code fragment')
|
|
index = matches[0]
|
|
else:
|
|
index = len(code) - len(code.lstrip())
|
|
marked.append((line_no, len(line[:index].encode('utf-8')) + 1))
|
|
return marked
|
|
|
|
|
|
def signature(air, d, site):
|
|
return (d['code'], d['kind'], site_key(air, d, site),
|
|
tuple(sorted((k, identity_class(air, d, d[k])) for k in (IDENTITIES - {'function', 'block', 'inst'}) & d.keys())),
|
|
tuple(x['role'] for x in d.get('related_locations', [])),
|
|
json.dumps(payload(d), sort_keys=True))
|
|
|
|
|
|
def annotation_map(annotated):
|
|
lines, mapping, pending = [], {}, None
|
|
for line in annotated.splitlines():
|
|
match = re.fullmatch(r'\s*; (?:(.+):)?(\d+):(\d+)-\d+:\d+', line)
|
|
if match:
|
|
pending = (match[1], int(match[2]), int(match[3]))
|
|
else:
|
|
lines.append(line)
|
|
mapping[len(lines)] = pending
|
|
pending = None
|
|
return '\n'.join(lines) + '\n', mapping
|
|
|
|
|
|
def operation_witnesses(air, diagnostics, required):
|
|
for d in diagnostics:
|
|
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL)
|
|
if not function:
|
|
raise ValueError('operation witness has no diagnostic function')
|
|
counts = Counter()
|
|
for line in function[0].splitlines():
|
|
line = line.split(';', 1)[0].strip()
|
|
if line and not line.startswith(('fn ', 'effects ')) and not line.endswith(':'):
|
|
counts[operation(line)] += 1
|
|
if any(counts[op] < minimum for op, minimum in required.items()):
|
|
raise ValueError('missing required operation witness in diagnostic function')
|
|
|
|
|
|
def verify_pair(aji, root, row, source):
|
|
air_path = CORPUS / row['air']
|
|
src_path = CORPUS / source
|
|
original = air_path.read_text()
|
|
air_ds = errors(aji, air_path)
|
|
ds = errors(aji, src_path)
|
|
source_text = src_path.read_text()
|
|
expected_positions = positions(source_text)
|
|
if not expected_positions or [(d['line'], d['col']) for d in ds] != expected_positions:
|
|
raise ValueError(f'{source}: diagnostics differ from marked source positions')
|
|
if row.get('lowering') == 'rejected':
|
|
if row['site'] != 'declaration':
|
|
raise ValueError('early rejection mode requires a declaration-site audit')
|
|
lowered = [load_json(x) for x in command(aji, 'lower', src_path, status=1).splitlines()]
|
|
if lowered != ds:
|
|
raise ValueError(f'{source}: lower/check early errors differ')
|
|
for d in ds:
|
|
line = source_text.splitlines()[d['line'] - 1].strip()
|
|
if not line.startswith(('struct ', 'enum ')) or d['file'] != str(src_path):
|
|
raise ValueError(f'{source}: early type error lacks a declaration position')
|
|
expected = Counter(signature(original, d, 'declaration') for d in air_ds)
|
|
found = Counter((d['code'], d['kind'], 'declaration',
|
|
(),
|
|
tuple(x['role'] for x in d.get('related_locations', [])),
|
|
json.dumps(payload(d), sort_keys=True)) for d in ds)
|
|
if expected != found:
|
|
raise ValueError(f'{source}: early type error has different rule facts')
|
|
return
|
|
canonical = command(aji, 'lower', src_path, status=0)
|
|
if command(aji, 'lower', src_path, status=0) != canonical:
|
|
raise ValueError(f'{source}: nondeterministic lowering')
|
|
annotated, mapping = annotation_map(command(aji, 'lower', '--annotate', src_path, status=0))
|
|
if annotated != canonical:
|
|
raise ValueError(f'{source}: annotations changed AIR')
|
|
raw = root / 'twin.air'
|
|
raw.write_text(canonical)
|
|
raw_ds = [load_json(line) for line in command(aji, 'check', raw, status=1).splitlines()]
|
|
# Spec 15 §10 keeps the first code per source location. Array bindings
|
|
# may emit both borrow.ref and slice.make for one invalid source borrow.
|
|
# Verify that exact projection; do not silently discard arbitrary extras.
|
|
projected, seen = [], set()
|
|
for rd in raw_ds:
|
|
origin = mapping[rd['line']]
|
|
if origin is None and row['site'] == 'function':
|
|
raw_name = re.match(r'fn @(\w+)', canonical.splitlines()[rd['line'] - 1])
|
|
declarations = [(i, line) for i, line in enumerate(source_text.splitlines(), 1)
|
|
if raw_name and re.match(r'\s*fn ' + re.escape(raw_name[1]) + r'\(', line)]
|
|
if len(declarations) != 1:
|
|
raise ValueError(f'{source}: budget header lacks a source declaration')
|
|
i, line = declarations[0]
|
|
origin = (str(src_path), i, len(line) - len(line.lstrip()) + 1)
|
|
if origin is None:
|
|
raise ValueError(f'{source}: raw diagnostic lacks a source mapping')
|
|
key = rd['code'], origin[0] or str(src_path), origin[1], origin[2]
|
|
if key not in seen:
|
|
projected.append(rd)
|
|
seen.add(key)
|
|
if len(projected) != len(ds):
|
|
raise ValueError(f'{source}: source/raw projected diagnostic counts differ')
|
|
for d, rd in zip(ds, projected):
|
|
if (d['air_line'], d['air_col'], d['code']) != (rd['line'], rd['col'], rd['code']):
|
|
raise ValueError(f'{source}: incorrect primary AIR position')
|
|
origin = mapping[d['air_line']]
|
|
if row['site'] == 'function':
|
|
# --annotate exposes block/instruction spans, not header spans.
|
|
# Budget sites instead have an independent marked declaration
|
|
# and must identify that same function in canonical AIR.
|
|
raw_line = canonical.splitlines()[d['air_line'] - 1]
|
|
source_line = source_text.splitlines()[d['line'] - 1]
|
|
raw_name = re.match(r'fn @(\w+)', raw_line)
|
|
source_name = re.match(r'\s*fn (\w+)', source_line)
|
|
if not raw_name or not source_name or raw_name[1] != source_name[1]:
|
|
raise ValueError(f'{source}: budget error names a different function')
|
|
elif origin is None or (d['line'], d['col']) != origin[1:]:
|
|
raise ValueError(f'{source}: missing/incorrect source position')
|
|
if d['file'] != str(src_path):
|
|
raise ValueError(f'{source}: wrong source file')
|
|
if payload(d) != payload(rd):
|
|
raise ValueError(f'{source}: mapping changed rule facts')
|
|
if [x['role'] for x in d.get('related_locations', [])] != [x['role'] for x in rd.get('related_locations', [])]:
|
|
raise ValueError(f'{source}: mapping changed related roles')
|
|
for related, rr in zip(d.get('related_locations', []), rd.get('related_locations', [])):
|
|
origin = mapping[related['air_line']]
|
|
if origin is None or (related['line'], related['col']) != origin[1:]:
|
|
raise ValueError(f'{source}: incorrect related source position')
|
|
if (related['air_line'], related['air_col']) != (rr['line'], rr['col']):
|
|
raise ValueError(f'{source}: incorrect related AIR position')
|
|
if row.get('required_ops'):
|
|
operation_witnesses(original, air_ds, row['required_ops'])
|
|
operation_witnesses(canonical, projected, row['required_ops'])
|
|
if Counter(signature(original, d, row['site']) for d in air_ds) != Counter(signature(canonical, d, row['site']) for d in projected):
|
|
raise ValueError(f'{source}: same codes but different offending operation/rule facts')
|
|
if row['site'] == 'function' and any('limit' not in d or 'max' not in d for d in ds):
|
|
raise ValueError(f'{source}: budget twin lacks stable limit facts')
|
|
|
|
|
|
def verify_analogue(aji, analogue):
|
|
p = CORPUS / analogue['source']
|
|
ds = errors(aji, p)
|
|
if [(d['line'], d['col']) for d in ds] != positions(p.read_text()):
|
|
raise ValueError(f"{analogue['source']}: analogue position changed")
|
|
for d in ds:
|
|
if any(d.get(k) != v for k, v in analogue.get('fields', {}).items()):
|
|
raise ValueError(f"{analogue['source']}: analogue rule facts changed")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--inventory', action='store_true')
|
|
parser.add_argument('--require-complete', action='store_true')
|
|
parser.add_argument('--aji', type=Path, default=ROOT / 'zig-out/bin/aji')
|
|
args = parser.parse_args()
|
|
try:
|
|
rows = inventory()
|
|
counts = Counter(row['kind'] for row in rows)
|
|
report = {'air_rejections': len(rows), 'counts': dict(counts),
|
|
'complete': counts['same_code'] == len(rows) and not args.inventory,
|
|
'verification': 'metadata_only' if args.inventory else 'compiled_pairs', 'cases': rows}
|
|
if args.inventory:
|
|
print(json.dumps(report, indent=2))
|
|
else:
|
|
with tempfile.TemporaryDirectory(prefix='aji-reject-twins-') as directory:
|
|
for row in rows:
|
|
for source in row['sources']:
|
|
verify_pair(args.aji, Path(directory), row, source)
|
|
for analogue in row.get('analogues', []):
|
|
verify_analogue(args.aji, analogue)
|
|
print(f"AIR rejection twins: {counts['same_code']}/{len(rows)} same-code cases verified; "
|
|
f"{counts['pending']} pending, {counts['source_error']} source-error analogues, "
|
|
f"{counts['air_only']} AIR-only. P6-7 complete: {report['complete']}.")
|
|
if args.require_complete and not report['complete']:
|
|
return 1
|
|
return 0
|
|
except (ValueError, KeyError, OSError, TypeError) as e:
|
|
print(f'rejection-twin check failed: {e}', file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|