Files
aji/tests/hosted/related_locations.py
T

244 lines
9.6 KiB
Python

#!/usr/bin/env python3
"""Factual borrow/spawn context in AIR, source, generics and package CLI."""
import json
from pathlib import Path
import re
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
checks = 0
covered = 0
def cli(*args, code=0):
global checks
p = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert p.returncode == code, (args, p.returncode, p.stdout, p.stderr)
checks += 1
return p.stdout
def decode_json(output):
def unique_object(pairs):
result = {}
for key, value in pairs:
assert key not in result, ('duplicate JSON member', key, output)
result[key] = value
return result
return json.loads(output, object_pairs_hook=unique_object)
def related(error, source=False):
global covered
field = 'task' if error['code'] == 'E4302' else 'conflicts_with'
if error['code'] not in ('E2101', 'E2104', 'E4302') or field not in error:
assert 'related_locations' not in error, error
return None
records = error['related_locations']
assert len(records) == 1, error
r = records[0]
role = 'task_spawn' if field == 'task' else 'conflicting_borrow'
assert r['role'] == role and r['value'] == error[field], error
assert list(error)[-1] == 'related_locations', error
keys = ['role', 'value']
if 'file' in r:
keys += ['file', 'line', 'col']
assert r['line'] >= 1 and r['col'] >= 1, r
if source:
keys += ['air_line', 'air_col']
assert list(r) == keys, r
covered += 1
return r
def air_origin(text, error):
r = related(error)
if r is None:
return
lines = text.splitlines()
line = lines[r['line'] - 1]
if r['role'] == 'task_spawn':
assert '= task.spawn ' in line and r['col'] == line.index('%') + 1, (line, r)
else:
# The selected value, rather than its backing root, defines context.
assert line[r['col'] - 1:].startswith(r['value']), (line, r)
assert '=' in line or ':' in line, (line, r)
assert r['file'] == error['file'], r
def source_check(root, *args):
errors = [decode_json(line) for line in cli('check', *args, code=1).splitlines()]
assert cli('check', *args, code=1) == cli('check', *args, code=1)
canonical = cli('lower', *args)
annotated = cli('lower', '--annotate', *args)
path = root / 'lowered.air'
path.write_text(canonical)
raw = [decode_json(line) for line in cli('check', path, code=1).splitlines()]
# Independently reconstruct the public annotation map, then use the
# unchanged primary-code/location deduplication to predict source output.
mapping = {}
actual_lines = []
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]))
continue
actual_lines.append(line)
mapping[len(actual_lines)] = pending
pending = None
assert '\n'.join(actual_lines) + '\n' == canonical
fallback = args[-1] if args[0] != '--manifest' else 'entry.aji'
expected = []
seen = set()
for d in raw:
air_origin(canonical, d)
primary = mapping.get(d['line'])
out = dict(d)
out['air_line'], out['air_col'] = d['line'], d['col']
out['file'], out['line'], out['col'] = (primary[0] or str(fallback), primary[1], primary[2]) if primary else (str(fallback), 1, 1)
if 'related_locations' in d:
r = d['related_locations'][0]
origin = mapping.get(r['line'])
context = {'role': r['role'], 'value': r['value']}
if origin:
context.update(file=origin[0] or str(fallback), line=origin[1], col=origin[2])
context.update(air_line=r['line'], air_col=r['col'])
out['related_locations'] = [context]
key = out['code'], out['file'], out['line'], out['col']
if key not in seen:
seen.add(key)
expected.append(out)
assert errors == expected, (args, errors, expected)
for d in errors:
related(d, source=True)
return errors
with tempfile.TemporaryDirectory(prefix='aji-related-') as directory:
root = Path(directory)
# Call-argument overlap selects the operand itself, exposing definitions
# that an ordinary root-access conflict often masks with an earlier borrow.
direct = [
('%p', '''fn @f(%p: mut<u64>) -> void
effects []
entry:
call @g(%p, %p)
ret
'''),
('%right', '''fn @f() -> void
effects []
entry:
%x = local.alloc array<u64, 2>
local.zero %x
%p = borrow.mut %x
%s = slice.make %p
%one = const.usize 1
%left, %right = slice.split %s, %one
call @h(%right, %right)
borrow.end %left
borrow.end %right
borrow.end %s
borrow.end %p
ret
'''),
('%returned', '''fn @view(%p: mut<u64>) -> mut<u64> from %p
effects []
entry:
%child = borrow.mut %p
ret %child
fn @f() -> void
effects []
entry:
%x = local.alloc u64
local.zero %x
%p = borrow.mut %x
%returned = call @view(%p)
call @g(%returned, %returned)
borrow.end %returned
borrow.end %p
ret
'''),
]
callees = '''fn @g(%a: mut<u64>, %b: mut<u64>) -> void
effects []
entry:
ret
fn @h(%a: slice_mut<u64>, %b: slice_mut<u64>) -> void
effects []
entry:
ret
'''
for identity, body in direct:
text = 'module definitions\nair 0\nlang 0.1\nfeatures [arrays, effects, ownership]\n' + body + callees
path = root / 'definitions.air'
path.write_text(text)
errors = [decode_json(line) for line in cli('check', path, code=1).splitlines()]
assert len(errors) == 1 and errors[0]['code'] == 'E2101', errors
air_origin(text, errors[0])
context = errors[0]['related_locations'][0]
assert context['value'] == identity, errors
definition = next((i, line.index(identity) + 1) for i, line in enumerate(text.splitlines(), 1)
if identity in line and (line.startswith('fn @f(') or identity in line.split('=')[0] and '=' in line))
assert (context['line'], context['col']) == definition, context
corpus = REPO / 'tests/conformance'
for path in sorted(corpus.rglob('*.air')):
text = path.read_text()
if not re.search(r'^; expect: reject .*E(?:2101|2104|4302)', text, re.M):
continue
errors = [decode_json(line) for line in cli('check', path, code=1).splitlines()]
for error in errors:
air_origin(text, error)
for path in sorted((corpus / 'source').rglob('*.aji')):
text = path.read_text()
if not re.search(r'^// expect: reject .*E(?:2101|2104|4302)', text, re.M):
continue
if re.search(r'^// module:', text, re.M):
continue # Explicit package tests below exercise linked provenance.
source_check(root, path)
errors = source_check(root, corpus / 'source/related_locations/borrow_live.aji')
assert errors[0]['line'] == 8 and errors[0]['related_locations'][0]['line'] == 7
assert decode_json(cli('run', '--fuel', '10000', corpus / 'source/related_locations/borrow_ended.aji'))['value'] == 2
# A returned view's definition is the caller's call, not the callee's from.
errors = source_check(root, corpus / 'source/borrow_returns/parent_access.aji')
context = errors[0]['related_locations'][0]
assert context['line'] == 6 and context['col'] == 92, context
entry, library, manifest = root / 'entry.aji', root / 'dep.aji', root / 'aji.toml'
manifest.write_text('[package]\nname = "related"\nversion = "1"\nentry = "entry.aji"\n[modules]\napp.dep = "dep.aji"\n')
entry.write_text('module app.entry\nimport app.dep;\nfn main()->u64 effects [] {app.dep.bad::<u64>()}\n')
library.write_text('module app.dep\nfn bad<T: Copy>()->u64 effects [] {\n'
' var data: [u64; 1] = [1u64];\n'
' ref view = data;\n'
' data[0] = 2u64;\n'
' return view[0];\n}\n')
errors = source_check(root, '--manifest', manifest)
context = errors[0]['related_locations'][0]
assert errors[0]['file'] == 'dep.aji' and errors[0]['line'] == 5
assert context['file'] == 'dep.aji' and context['line'] == 4 and context['col'] == 5
entry.write_text(entry.read_text().replace('bad::<u64>', 'bad'))
library.write_text(library.read_text().replace('bad<T: Copy>', 'bad'))
errors = source_check(root, '--manifest', manifest)
assert errors[0]['related_locations'][0]['file'] == 'dep.aji'
# Codes outside the scope keep the old envelope.
other = root / 'other.aji'
other.write_text('module other fn main()->u64 effects [] {return true;}')
assert 'related_locations' not in decode_json(cli('check', other, code=1))
for fixture, code, kind, field, value in (
('phase2/reject/unknown_narrowing_form.air', 'E3202', 'capability.widen', 'capability_kind', 'io.write'),
('phase3/reject/sync_unlock_live_borrow.air', 'E2102', 'borrow.outlives_owner', 'guard', '%g'),
('source/diagnostic_envelope/capability_kind_unknown.aji', 'E7002', 'source.unknown_name', 'capability_kind', 'unknown'),
):
error = decode_json(cli('check', corpus / fixture, code=1))
assert error['code'] == code and error['kind'] == kind and error[field] == value, error
if field == 'guard':
assert error['borrow'] == '%p', error
cli('check', corpus / 'source/diagnostic_envelope/capability_kind_known.aji')
assert covered > 0
print(f'related location CLI passed ({checks} checks; {covered} context records)')