601 lines
31 KiB
Python
601 lines
31 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 hashlib
|
|
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',
|
|
'callee', 'argument', 'task_function', 'operand'}
|
|
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', 'exact_ops', 'required_identity_uses',
|
|
'match_type_declarations', 'early_context', 'audited_context',
|
|
'feature_header_context'}
|
|
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 'exact_ops' in review and (review['exact_ops'] is not True or not witnesses):
|
|
raise ValueError(f'{name}: exact operation witness needs nonempty required_ops')
|
|
uses = review.get('required_identity_uses', {})
|
|
if not isinstance(uses, dict) or any(
|
|
field not in IDENTITIES - {'function', 'block', 'inst', 'callee', 'task_function'} or
|
|
not isinstance(op, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_.]*', op)
|
|
for field, op in uses.items()):
|
|
raise ValueError(f'{name}: invalid diagnostic-identity use witness')
|
|
if review.get('lowering') not in {None, 'rejected'}:
|
|
raise ValueError(f'{name}: invalid lowering mode')
|
|
if 'match_type_declarations' in review and review['match_type_declarations'] is not True:
|
|
raise ValueError(f'{name}: type-declaration witness must be true')
|
|
if 'feature_header_context' in review and (
|
|
review['feature_header_context'] is not True or expected != ['E0006']):
|
|
raise ValueError(f'{name}: feature-header context needs one E0006 rejection')
|
|
if review['kind'] not in {'same_code', 'source_error', 'air_only'}:
|
|
raise ValueError(f'{name}: invalid classification')
|
|
if ({'required_ops', 'exact_ops', 'required_identity_uses', 'match_type_declarations',
|
|
'audited_context', 'feature_header_context'} & review.keys()) and (
|
|
review['kind'] != 'same_code' or review.get('lowering') == 'rejected'):
|
|
raise ValueError(f'{name}: AIR witnesses require a lowered same-code pair')
|
|
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')
|
|
if review.get('lowering') == 'rejected':
|
|
context = review.get('early_context')
|
|
if (review['kind'] != 'same_code' or not isinstance(context, dict) or
|
|
set(context) != {'air', 'sources'} or
|
|
not isinstance(context['sources'], dict) or
|
|
set(context['sources']) != set(sources) or
|
|
any(not isinstance(x, str) or not re.fullmatch(r'[0-9a-f]{64}', x)
|
|
for x in [context['air'], *context['sources'].values()])):
|
|
raise ValueError(f'{name}: early rejection needs audited AIR/source fingerprints')
|
|
elif 'early_context' in review:
|
|
raise ValueError(f'{name}: early context requires rejected lowering')
|
|
if 'audited_context' in review:
|
|
context = review['audited_context']
|
|
if (not isinstance(context, dict) or set(context) != {'air', 'sources', 'lowered'} or
|
|
any(not isinstance(context[key], dict) or set(context[key]) != set(sources)
|
|
for key in ('sources', 'lowered')) or
|
|
any(not isinstance(x, str) or not re.fullmatch(r'[0-9a-f]{64}', x)
|
|
for x in [context['air'], *context['sources'].values(),
|
|
*context['lowered'].values()])):
|
|
raise ValueError(f'{name}: lowered context needs audited AIR/source/lowered fingerprints')
|
|
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, allow_swapped_enum=False):
|
|
"""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.
|
|
island.borrow and mutex.borrow are explicit borrow producers.
|
|
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', 'island.borrow', 'mutex.borrow'}:
|
|
return 'borrow'
|
|
if op in producers:
|
|
return producers[op]
|
|
if op == 'value.swap' and allow_swapped_enum:
|
|
return swapped_enum_class(air, d, value)
|
|
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 function_declaration(air, name):
|
|
declaration = re.search(r'^fn @' + re.escape(name) +
|
|
r'\(([^)]*)\)([^\n]*)\n\s*effects \[([^]]*)\]', air, re.MULTILINE)
|
|
if not declaration:
|
|
raise ValueError(f'function lacks an audited declaration: {name}')
|
|
parameters, result, effects = declaration.groups()
|
|
return parameters, result.strip(), tuple(sorted({x.strip() for x in effects.split(',') if x.strip()}))
|
|
|
|
|
|
def swapped_enum_class(air, d, value):
|
|
# Only the reviewed E3002 value.swap result role is supported. Resolve a
|
|
# direct enum constructor; this is not a type/property derivation.
|
|
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)',
|
|
air, re.MULTILINE | re.DOTALL)
|
|
if not function:
|
|
raise ValueError('swapped enum lacks a defining function')
|
|
text = re.sub(r';[^\n]*', '', function[0])
|
|
def definition(name):
|
|
definitions = re.findall(r'^\s*' + re.escape(name) + r'\s*=\s*([^\n]+)',
|
|
text, re.MULTILINE)
|
|
if len(definitions) != 1:
|
|
raise ValueError('swapped enum lacks a unique direct definition')
|
|
return definitions[0].strip()
|
|
swap = re.fullmatch(r'value\.swap (%[A-Za-z0-9_]+), (%[A-Za-z0-9_]+)', definition(value))
|
|
if not swap:
|
|
raise ValueError('unsupported swapped enum result')
|
|
replacement = re.fullmatch(r'enum\.make (@[A-Za-z][A-Za-z0-9_]*)\.[A-Za-z0-9_]+\([^\n]*\)',
|
|
definition(swap[2]))
|
|
if not replacement or not re.search(r'^type ' + re.escape(replacement[1]) + r' = enum \{', air, re.MULTILINE):
|
|
raise ValueError('swapped enum replacement lacks a named enum declaration')
|
|
return 'swap_enum ' + replacement[1]
|
|
|
|
|
|
def identity_fact(air, d, field):
|
|
if field == 'operand':
|
|
# E4202's operand is an SSA identity, tied to the reported load.
|
|
# Other ordinary-access forms need their own rule audit.
|
|
if d['code'] != 'E4202' or d.get('use') != 'atomic.load':
|
|
raise ValueError('unsupported atomic operand identity rule')
|
|
line = air.splitlines()[d['line'] - 1].split(';', 1)[0]
|
|
rhs = line.split('=', 1)[-1].strip()
|
|
if not re.fullmatch(r'load\s+' + re.escape(d[field]), rhs):
|
|
raise ValueError('atomic operand is not the offending load operand')
|
|
root = identity_class(air, d, d[field])
|
|
if root != 'borrow':
|
|
raise ValueError('ordinary atomic load operand lacks a borrow definition')
|
|
return root
|
|
if field == 'callee':
|
|
# Parameter/result types do not decide the flat-effect rule.
|
|
if d['code'] != 'E3101':
|
|
raise ValueError('unsupported callee identity rule')
|
|
return function_declaration(air, d[field])[2]
|
|
if field == 'task_function':
|
|
if d['code'] not in {'E4001', 'E4002'}:
|
|
raise ValueError('unsupported worker identity rule')
|
|
_, result, _ = function_declaration(air, d[field])
|
|
if 'argument' in d:
|
|
# checkSpawn selects Send/Share from this argument's parameter
|
|
# type. Its complete type remains a stable diagnostic fact.
|
|
if not isinstance(d.get('type'), str):
|
|
raise ValueError('task argument rule lacks its type fact')
|
|
return 'argument_Send' if d['code'] == 'E4001' else 'argument_Share'
|
|
if d['code'] != 'E4001':
|
|
raise ValueError('unsupported worker-result identity rule')
|
|
return 'result_Send', result
|
|
if field == 'argument' and d['code'] not in {'E4001', 'E4002'}:
|
|
raise ValueError('unsupported argument identity rule')
|
|
return identity_class(air, d, d[field],
|
|
allow_swapped_enum=field == 'borrow' and d['code'] == 'E3002')
|
|
|
|
|
|
def feature_header_facts(air, d):
|
|
# Compare the missing closure, after checking each module's repair line.
|
|
# The verifier supplies closure; this does not compute dependencies.
|
|
if d['code'] != 'E0006' or d.get('reason') != 'feature_not_declared':
|
|
raise ValueError('unsupported feature-header context rule')
|
|
uncommented = re.sub(r';[^\n]*', '', air)
|
|
headers = re.findall(r'^\s*features \[([^]\n]*)\]\s*$', uncommented, re.MULTILINE)
|
|
if len(headers) != 1 or not isinstance(d.get('closure'), str):
|
|
raise ValueError('feature-header context lacks a unique header/closure')
|
|
declared = [x.strip() for x in headers[0].split(',')] if headers[0].strip() else []
|
|
closure = [x.strip() for x in d['closure'].split(',')]
|
|
if (any(not re.fullmatch(r'[a-z][a-z0-9_]*', x) for x in declared + closure) or
|
|
len(set(declared)) != len(declared) or len(set(closure)) != len(closure) or
|
|
d.get('feature') not in closure or d['feature'] in declared):
|
|
raise ValueError('invalid declared/missing feature context')
|
|
expected = 'features [' + ', '.join(sorted(set(declared) | set(closure))) + ']'
|
|
if d.get('canonical_header') != expected:
|
|
raise ValueError('feature repair header differs from declared features and closure')
|
|
facts = payload(d)
|
|
del facts['canonical_header']
|
|
facts['missing_feature_closure'] = sorted(set(closure) - set(declared))
|
|
return facts
|
|
|
|
|
|
def signature(air, d, site, feature_header_context=False):
|
|
return (d['code'], d['kind'], site_key(air, d, site),
|
|
tuple(sorted((k, identity_fact(air, d, k))
|
|
for k in (IDENTITIES - {'function', 'block', 'inst'}) & d.keys())),
|
|
tuple(x['role'] for x in d.get('related_locations', [])),
|
|
json.dumps(feature_header_facts(air, d) if feature_header_context else 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, exact=False, identity_uses=None):
|
|
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()
|
|
operands = {}
|
|
for line in function[0].splitlines():
|
|
line = line.split(';', 1)[0].strip()
|
|
if line and not line.startswith(('fn ', 'effects ')) and not line.endswith(':'):
|
|
op = operation(line)
|
|
counts[op] += 1
|
|
rhs = line.split('=', 1)[1] if line.startswith('%') and '=' in line else line
|
|
operands.setdefault(op, set()).update(re.findall(r'%[A-Za-z_][\w.]*', rhs))
|
|
if any(counts[op] < minimum for op, minimum in required.items()):
|
|
raise ValueError('missing required operation witness in diagnostic function')
|
|
if exact and counts != Counter(required):
|
|
raise ValueError('different exact operation witness in diagnostic function')
|
|
if any(d.get(field) not in operands.get(op, set())
|
|
for field, op in (identity_uses or {}).items()):
|
|
raise ValueError('missing diagnostic-identity use witness')
|
|
|
|
|
|
def header_origin(air_line, source, path, site):
|
|
# --annotate contains instruction/block spans only. For non-generic
|
|
# headers, resolve the exact canonical name to one source declaration.
|
|
air_pattern, source_pattern = (
|
|
(r'fn @(\w+)\(', r'fn ')
|
|
if site == 'function' else
|
|
(r'type @(\w+)\s*=', r'(?:struct|enum) '))
|
|
name = re.match(air_pattern, air_line)
|
|
declarations = [(i, line) for i, line in enumerate(source.splitlines(), 1)
|
|
if name and re.match(r'\s*' + source_pattern + re.escape(name[1]) + r'\b', line)]
|
|
if len(declarations) != 1:
|
|
raise ValueError(f'{path}: budget header lacks a unique matching source declaration')
|
|
i, line = declarations[0]
|
|
return str(path), i, len(line[:len(line) - len(line.lstrip())].encode('utf-8')) + 1
|
|
|
|
|
|
def type_declarations(air):
|
|
# A fixture-context witness, not a type/layout evaluator. Preserve the
|
|
# complete named declaration table, ignoring only comments/whitespace.
|
|
declarations = {}
|
|
for line in air.splitlines():
|
|
line = line.split(';', 1)[0].strip()
|
|
if not line.startswith('type '):
|
|
continue
|
|
declaration = re.fullmatch(r'type @([\w.]+)\s*=\s*(.+)', line)
|
|
if not declaration or declaration[1] in declarations:
|
|
raise ValueError('unsupported/duplicate type declaration witness')
|
|
declarations[declaration[1]] = re.sub(r'\s+', '', declaration[2])
|
|
return declarations
|
|
|
|
|
|
def verify_pair(aji, root, row, source):
|
|
air_path = CORPUS / row['air']
|
|
src_path = CORPUS / source
|
|
context = row.get('audited_context')
|
|
if context:
|
|
# Preserve a manually reviewed CFG artifact, not inferred loan facts.
|
|
if hashlib.sha256(air_path.read_bytes()).hexdigest() != context['air']:
|
|
raise ValueError('audited AIR changed; a new context audit is required')
|
|
if hashlib.sha256(src_path.read_bytes()).hexdigest() != context['sources'][source]:
|
|
raise ValueError('audited source changed; a new context audit is required')
|
|
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')
|
|
# No canonical AIR exists. Pin both manually audited artifacts rather
|
|
# than inventing a second source parser to compare cycle shapes.
|
|
context = row['early_context']
|
|
if hashlib.sha256(air_path.read_bytes()).hexdigest() != context['air']:
|
|
raise ValueError('audited early AIR changed; a new context audit is required')
|
|
if hashlib.sha256(src_path.read_bytes()).hexdigest() != context['sources'][source]:
|
|
raise ValueError('audited early source changed; a new context audit is required')
|
|
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 context and hashlib.sha256(canonical.encode('utf-8')).hexdigest() != context['lowered'][source]:
|
|
raise ValueError('audited lowering changed; a new context audit is required')
|
|
if row.get('match_type_declarations') and type_declarations(original) != type_declarations(canonical):
|
|
raise ValueError(f'{source}: different type-declaration context')
|
|
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'] in {'function', 'declaration'}:
|
|
origin = header_origin(canonical.splitlines()[rd['line'] - 1],
|
|
source_text, src_path, row['site'])
|
|
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 origin is None and row['site'] in {'function', 'declaration'}:
|
|
origin = header_origin(canonical.splitlines()[d['air_line'] - 1],
|
|
source_text, src_path, row['site'])
|
|
if 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 {k: d[k] for k in IDENTITIES & d.keys()} != {k: rd[k] for k in IDENTITIES & rd.keys()}:
|
|
raise ValueError(f'{source}: mapping changed diagnostic identities')
|
|
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', [])):
|
|
if related.get('value') != rr.get('value'):
|
|
raise ValueError(f'{source}: mapping changed related identity')
|
|
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') or row.get('required_identity_uses'):
|
|
for air, diagnostics in ((original, air_ds), (canonical, projected)):
|
|
operation_witnesses(air, diagnostics, row.get('required_ops', {}),
|
|
row.get('exact_ops', False), row.get('required_identity_uses'))
|
|
feature_context = row.get('feature_header_context', False)
|
|
if Counter(signature(original, d, row['site'], feature_context) for d in air_ds) != Counter(signature(canonical, d, row['site'], feature_context) for d in projected):
|
|
raise ValueError(f'{source}: same codes but different offending operation/rule facts')
|
|
if any(d['code'] == 'E5101' and ('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())
|