tests: preserve rejection contexts and normalize callee effects
This commit is contained in:
1 parent
06d8a1a76a
commit
fd92604f36
11 files changed
+344
-35
No files matched your search
@@ -8,6 +8,7 @@ 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
|
||||
@@ -19,7 +20,7 @@ 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'}
|
||||
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from', 'callee'}
|
||||
ENVELOPE = {'code', 'kind', 'severity', 'file', 'line', 'col', 'air_line',
|
||||
'air_col', 'message', 'related_locations'}
|
||||
|
||||
@@ -84,7 +85,8 @@ def inventory():
|
||||
if review is None:
|
||||
row = {'air': name, 'codes': expected, 'kind': 'pending', 'sources': []}
|
||||
else:
|
||||
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues', 'required_ops'}
|
||||
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues',
|
||||
'required_ops', 'match_type_declarations', 'early_context'}
|
||||
if set(review) - allowed:
|
||||
raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}')
|
||||
witnesses = review.get('required_ops', {})
|
||||
@@ -95,8 +97,13 @@ def inventory():
|
||||
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 'match_type_declarations' in review and review['match_type_declarations'] is not True:
|
||||
raise ValueError(f'{name}: type-declaration witness must be true')
|
||||
if review['kind'] not in {'same_code', 'source_error', 'air_only'}:
|
||||
raise ValueError(f'{name}: invalid classification')
|
||||
if ('required_ops' in review or 'match_type_declarations' in review) 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()
|
||||
@@ -109,6 +116,17 @@ def inventory():
|
||||
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')
|
||||
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')
|
||||
@@ -231,9 +249,23 @@ def positions(source):
|
||||
return marked
|
||||
|
||||
|
||||
def callee_effects(air, d):
|
||||
# For E3101, the callee's explicit flat effect set is the rule-relevant
|
||||
# contract. Parameter/return types do not decide this effect rule.
|
||||
if d['code'] != 'E3101':
|
||||
raise ValueError('unsupported callee identity rule')
|
||||
name = d['callee']
|
||||
declaration = re.search(r'^fn @' + re.escape(name) +
|
||||
r'\(([^)]*)\)([^\n]*)\n\s*effects \[([^]]*)\]', air, re.MULTILINE)
|
||||
if not declaration:
|
||||
raise ValueError(f'callee lacks an audited declaration: {name}')
|
||||
return tuple(sorted(x.strip() for x in declaration[3].split(',') if x.strip()))
|
||||
|
||||
|
||||
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(sorted((k, callee_effects(air, d) if k == 'callee' else 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))
|
||||
|
||||
@@ -265,6 +297,37 @@ def operation_witnesses(air, diagnostics, required):
|
||||
raise ValueError('missing required operation witness in diagnostic function')
|
||||
|
||||
|
||||
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
|
||||
@@ -278,6 +341,13 @@ def verify_pair(aji, root, row, source):
|
||||
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')
|
||||
@@ -294,6 +364,8 @@ def verify_pair(aji, root, row, source):
|
||||
raise ValueError(f'{source}: early type error has different rule facts')
|
||||
return
|
||||
canonical = command(aji, 'lower', src_path, status=0)
|
||||
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))
|
||||
@@ -308,14 +380,9 @@ def verify_pair(aji, root, row, source):
|
||||
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 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]
|
||||
@@ -328,17 +395,10 @@ def verify_pair(aji, root, row, source):
|
||||
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:]:
|
||||
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')
|
||||
@@ -357,7 +417,7 @@ def verify_pair(aji, root, row, source):
|
||||
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):
|
||||
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')
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user