diag: add factual related borrow and task locations
This commit is contained in:
1 parent
dbd9763713
commit
8ee0f4c2bf
27 files changed
+659
-18
No files matched your search
@@ -0,0 +1,18 @@
|
||||
; expect: reject E2101
|
||||
; phase: 1
|
||||
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
|
||||
module related.rejected
|
||||
air 0
|
||||
lang 0.1
|
||||
features [ownership]
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%data = local.alloc u64
|
||||
local.zero %data
|
||||
%view = borrow.ref %data
|
||||
%two = const.u64 2
|
||||
local.store %data, %two
|
||||
%result = load %view
|
||||
borrow.end %view
|
||||
ret %result
|
||||
@@ -0,0 +1,23 @@
|
||||
; expect: run
|
||||
; result: 2
|
||||
; phase: 1
|
||||
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
|
||||
module related.valid
|
||||
air 0
|
||||
lang 0.1
|
||||
features [ownership]
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%data = local.alloc u64
|
||||
%one = const.u64 1
|
||||
local.store %data, %one
|
||||
%view = borrow.ref %data
|
||||
%read = load %view
|
||||
%same = eq.u64 %read, %one
|
||||
assert %same
|
||||
borrow.end %view
|
||||
%two = const.u64 2
|
||||
local.store %data, %two
|
||||
%result = local.load %data
|
||||
ret %result
|
||||
@@ -0,0 +1,32 @@
|
||||
; expect: reject E4302
|
||||
; phase: 3
|
||||
; spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
|
||||
module related.cancel_twice
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
fn @main() -> u8
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%x = local.alloc u8
|
||||
local.zero %x
|
||||
%r = borrow.ref %x
|
||||
%s = task.scope.begin
|
||||
%t = task.spawn %s, @worker(%r)
|
||||
task.join.cancel %t, ok -> @joined, cancelled -> @retry
|
||||
retry(%back: task<u8>):
|
||||
task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
|
||||
joined(%v: u8):
|
||||
task.scope.end %s
|
||||
borrow.end %r
|
||||
ret %v
|
||||
cancelled(%back2: task<u8>):
|
||||
borrow.end %r
|
||||
%v2 = task.join %back2
|
||||
task.scope.end %s
|
||||
ret %v2
|
||||
fn @worker(%p: ref<u8>) -> u8
|
||||
effects []
|
||||
entry:
|
||||
%v = load %p
|
||||
ret %v
|
||||
@@ -0,0 +1,34 @@
|
||||
; expect: run
|
||||
; result: 0
|
||||
; schedules: 20
|
||||
; phase: 3
|
||||
; spec: docs/spec/04-concurrency-and-atomics.md §34
|
||||
module related.cancel_twice_joined
|
||||
air 0
|
||||
lang 0.1
|
||||
features [cancellation, effects, ownership, tasks]
|
||||
fn @main() -> u8
|
||||
effects [task.spawn, task.wait]
|
||||
entry:
|
||||
%x = local.alloc u8
|
||||
local.zero %x
|
||||
%r = borrow.ref %x
|
||||
%s = task.scope.begin
|
||||
%t = task.spawn %s, @worker(%r)
|
||||
task.join.cancel %t, ok -> @joined, cancelled -> @retry
|
||||
retry(%back: task<u8>):
|
||||
task.join.cancel %back, ok -> @joined, cancelled -> @cancelled
|
||||
joined(%v: u8):
|
||||
task.scope.end %s
|
||||
borrow.end %r
|
||||
ret %v
|
||||
cancelled(%back2: task<u8>):
|
||||
%v2 = task.join %back2
|
||||
borrow.end %r
|
||||
task.scope.end %s
|
||||
ret %v2
|
||||
fn @worker(%p: ref<u8>) -> u8
|
||||
effects []
|
||||
entry:
|
||||
%v = load %p
|
||||
ret %v
|
||||
@@ -0,0 +1,11 @@
|
||||
// expect: run
|
||||
// result: 2
|
||||
// phase: 6
|
||||
// spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
|
||||
module related.valid
|
||||
fn main() -> u64 effects [] {
|
||||
var data: [u64; 1] = [1u64];
|
||||
{ ref view = data; assert(view[0] == 1u64); }
|
||||
data[0] = 2u64;
|
||||
return data[0];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// expect: reject E2101
|
||||
// phase: 6
|
||||
// spec: docs/spec/10-diagnostics-and-agent-protocol.md §2
|
||||
module related.rejected
|
||||
fn main() -> u64 effects [] {
|
||||
var data: [u64; 1] = [1u64];
|
||||
ref view = data;
|
||||
data[0] = 2u64;
|
||||
return view[0];
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
#!/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 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 = [json.loads(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 = [json.loads(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 = [json.loads(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 = [json.loads(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 json.loads(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 json.loads(cli('check', other, code=1))
|
||||
|
||||
assert covered > 0
|
||||
print(f'related location CLI passed ({checks} checks; {covered} context records)')
|
||||
Reference in new issue
Block a user