From 09fbf8a5bcf60ad504428c0892b70a0b72339ad4 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Thu, 8 Oct 2026 17:17:08 +0300 Subject: [PATCH] verifier: preserve resource obligations across CFG handoff --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + docs/agent/README.md | 4 +- docs/design/decisions.md | 12 + docs/design/open-questions.md | 6 + docs/plan/phase-6-source-language.md | 6 + docs/spec/04-concurrency-and-atomics.md | 6 + src/verifier/borrow.zig | 286 ++++++++++++++---- src/verifier/provenance.zig | 100 ++++++ .../reject/cfg_provenance_cancel_arg.air | 41 +++ .../reject/cfg_provenance_guard_parent.air | 27 ++ .../reject/cfg_provenance_loan_access.air | 37 +++ .../reject/cfg_provenance_loan_backedge.air | 42 +++ .../phase3/reject/cfg_provenance_loan_br.air | 35 +++ .../phase3/reject/cfg_provenance_loan_cbr.air | 41 +++ .../reject/cfg_provenance_loan_join.air | 41 +++ .../reject/cfg_provenance_loan_switch.air | 41 +++ .../reject/cfg_provenance_scope_alone.air | 31 ++ .../reject/cfg_provenance_scope_task.air | 31 ++ .../reject/cfg_provenance_shield_order.air | 19 ++ .../cfg_provenance_shield_stack_join.air | 21 ++ .../phase3/run/cfg_provenance_cancel_arg.air | 38 +++ .../run/cfg_provenance_correlated_scopes.air | 41 +++ .../run/cfg_provenance_guard_handoff.air | 33 ++ .../run/cfg_provenance_loan_returned.air | 39 +++ .../run/cfg_provenance_shield_handoff.air | 22 ++ .../phase3/run/cfg_provenance_task_loop.air | 42 +++ .../cancel_join_keeps_loans.aji | 27 ++ .../cancel_join_twice_keeps_spawn.aji | 33 ++ .../cfg_provenance/cancel_task_block.aji | 28 ++ .../source/cfg_provenance/task_block.aji | 22 ++ .../source/cfg_provenance/task_branch.aji | 23 ++ .../cfg_provenance/tasks_end_lent_borrow.aji | 20 ++ tests/hosted/source_cfg_provenance.py | 137 +++++++++ 34 files changed, 1267 insertions(+), 67 deletions(-) create mode 100644 src/verifier/provenance.zig create mode 100644 tests/conformance/phase3/reject/cfg_provenance_cancel_arg.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_guard_parent.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_access.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_backedge.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_br.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_cbr.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_join.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_loan_switch.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_scope_alone.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_scope_task.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_shield_order.air create mode 100644 tests/conformance/phase3/reject/cfg_provenance_shield_stack_join.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_cancel_arg.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_correlated_scopes.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_guard_handoff.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_loan_returned.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_shield_handoff.air create mode 100644 tests/conformance/phase3/run/cfg_provenance_task_loop.air create mode 100644 tests/conformance/source/cfg_provenance/cancel_join_keeps_loans.aji create mode 100644 tests/conformance/source/cfg_provenance/cancel_join_twice_keeps_spawn.aji create mode 100644 tests/conformance/source/cfg_provenance/cancel_task_block.aji create mode 100644 tests/conformance/source/cfg_provenance/task_block.aji create mode 100644 tests/conformance/source/cfg_provenance/task_branch.aji create mode 100644 tests/conformance/source/cfg_provenance/tasks_end_lent_borrow.aji create mode 100644 tests/hosted/source_cfg_provenance.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 776129a..e09d7bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,7 @@ jobs: - run: python3 tests/hosted/source_nominal_queries.py - run: python3 tests/hosted/source_grammar.py - run: python3 tests/hosted/source_effect_names.py + - run: python3 tests/hosted/source_cfg_provenance.py - run: python3 tests/hosted/examples.py --stress 200 - run: python3 tests/hosted/source_static_functions.py - run: python3 tests/hosted/source_linear.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8aab575..2ca66eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,6 +33,7 @@ python3 tests/hosted/source_store_modes.py # exclusive places, source positions, python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance +python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors diff --git a/docs/agent/README.md b/docs/agent/README.md index 1ca463b..321b585 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -169,4 +169,6 @@ Q-048 source access modes (cl100k): Quick Reference stays 8,948; other source do DD-022 grammar surface (cl100k): Quick Reference stays 8,948; other source docs 67,343 → 68,219 (+876), full source 76,291 → 77,167 (+1.15%). o200k groups are 8,984 / 68,422 / 77,406; Qwen2.5 9,226 / 69,887 / 79,113. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing syntax and ordered parsing choices replace incomplete grammar descriptions. Empty qualified enum payload lists now reject E7001; accepted public-source canonical AIR is preserved. No new programming concept, feature, diagnostic code or verifier/runtime state is added. The grammar stays a reference read on demand; no empirical MCC benefit is claimed. -Q-051 source effect names (DD-023, cl100k): Quick Reference 8,948 → 8,955 (+7); other source docs 68,219 → 68,323 (+104), full source 77,167 → 77,278 (+0.14%). o200k groups are 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227. AIR grows 47,445 → 47,458 (+13), 184,628 → 184,678 bytes, through the shared E7002 registry description; library/std.md is unchanged. Unknown effects use existing E7002 with structured `name`/`effect`, replacing erroneous source E7900 or E0006. Accepted canonical AIR and authority/effect semantics are preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added; no empirical MCC benefit is claimed. +Q-051 source effect names (DD-023, cl100k): Quick Reference 8,948 → 8,955 (+7); other source docs 68,219 → 68,323 (+104), full source 77,167 → 77,278 (+0.14%). o200k groups are 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227. The AIR copy in the source bundle grows 47,445 → 47,458 (+13); canonical AIR bundle bytes grow 184,628 → 184,678, through the shared E7002 registry description; library/std.md is unchanged. Unknown effects use existing E7002 with structured `name`/`effect`, replacing erroneous source E7900 or E0006. Accepted canonical AIR and authority/effect semantics are preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added; no empirical MCC benefit is claimed. + +Q-052 CFG resource provenance (DD-024): Quick Reference and other/full source docs remain 8,955 / 68,323 / 77,278 cl100k (o200k 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227); std is unchanged. Canonical AIR grows 184,678 → 185,220 bytes and 47,385 → 47,476 cl100k (+91), 47,540 → 47,631 o200k (+91), 48,917 → 49,009 Qwen2.5 (+92). The separately wrapped source-bundle AIR copy grows 47,458 → 47,549 cl100k. The added sentences clarify preservation of existing task/scope, guard and shield obligations through block arguments. No new agent concept, syntax, feature or diagnostic is introduced. Sparse implementation relations replace incomplete SSA metadata; verifier acceptance now enforces existing safety rules. No empirical MCC benefit is claimed. diff --git a/docs/design/decisions.md b/docs/design/decisions.md index 9f10bcb..a48e84a 100644 --- a/docs/design/decisions.md +++ b/docs/design/decisions.md @@ -143,3 +143,15 @@ Q-050 corrects empty parentheses on qualified enum variants, contrary to spec 15 Q-051 validates ordinary effect names before body lowering using the existing closed registry. Templates/static contracts use the same E7002 with `name` and `effect`; legacy E0006 without a feature reason was incorrect. Function/template positions remain declaration starts, static contracts use their parameter start. Ordinary parameter/return/from checks retain priority; existing template/header ordering remains. Unknown effects cannot generate malformed AIR or E7900. AIR E0004 and its registry contract are unchanged. Only invalid-source codes/priority/fields change. Registered effects, explicit authority, effect coverage, duplicate-list set semantics and static-contract uniqueness remain unchanged; no code, reason, syntax, AIR feature, verifier/runtime or ownership/concurrency state is added. Positive/rejected source tests and CLI/package tests cover headers, unused declarations, priority, missing-effect/capability diagnostics, formatting and source/AIR execution. Budget growth is measured in docs/agent/README.md. This completes this diagnostic correction, not P6-2 or an empirical MCC claim. + +## DD-024 — Resource obligations survive SSA handoff + +Q-052 corrects the verifier's loss of task loans/scopes, guard parents and shield order at block parameters. The preserved invariants are no ending or conflicting access to a loan before its task is joined, no live child at scope completion, no ending a mutex borrow while its guard lives, and properly nested shields. Spec 04 clarifies the already permitted function-local transfer; no AIR feature or new semantic restriction is introduced. + +The verifier records static definition/consumption events, solves sparse relations over the CFG to a fixed point, then checks instructions in the existing diagnostic order. Edge transfer renames both positions simultaneously: a scope association follows the scope even if its task is not passed. This preserves correlated permutations of scopes and tasks; independent origin sets would reject valid code. Task/loan/guard alternatives join by union, while the existing shield-stack equality rule is checked separately. Definition sites retain diagnostic spawn positions. The collecting walk excludes relational error recovery; extra facts about subsequently rejected/dead resources are filtered by final liveness. Functions without these resource types retain one walk. + +Valid: forward a task and its scope, join the renamed task, then end the renamed scope; end renamed shields inner first; unlock a renamed guard before ending its mutex borrow. Rejected: end the lent borrow or store through its exclusive loan before joining the forwarded task; end a forwarded scope with a live child; end the guard's parent borrow; end the outer forwarded shield first. Source/AIR conformance fixtures cover these cases, cancelled joins, joins with different loan origins, loops and correlated scope/task permutations. + +Diagnostic impact: the existing E4302/E4101/E4301/E2102/E4305/E3002 rules now apply after handoff. A transferred live child reports E4301 in preference to E3002. E4302 identifies the current handle and the original spawn. Incompatible shield stacks report E3002 with a shield identity; a subsequent wrong end can also report E4305. New codes, reasons and repairs are unnecessary. + +Runtime and deterministic interpreter behavior are unchanged: transfer already moves the same resource, and a cancelled join already returns the same task. Compatibility changes only for violations formerly accepted, or reported with a generic leak after provenance was lost; valid lowering remains unchanged. Counted rotation tests bound fixed-point visits, scheduler/collection tests cover execution, and CLI tests cover exact source/package/generic positions and canonical AIR. Bundle growth is recorded in docs/agent/README.md. This strengthens verification without claiming an empirical MCC improvement or completing P6-7. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index dfd2cbc..479829e 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -374,3 +374,9 @@ The parser accepted `E::Empty()` and the corresponding match pattern, although s An ordinary function declaring `effects [bogus.effect]` reaches AIR and reports E7900 with `air_code: E0004`; templates/static contracts reject the same known-invalid effect directly with E0006. Effect membership is determined entirely from source and the registry. A P6-2 task should align ordinary signature validation with the existing template contract, preserving effect/capability semantics and checking diagnostic priority/positions. No implementation is included in DD-022. **Resolved (DD-023, spec 15 §9):** ordinary signatures validate the existing effect registry before body lowering; templates/static contracts replace the incorrect E0006 with E7002. Fields `name` and `effect` identify the atom without prose; locations retain declaration/parameter starts. Signature/type/from and template/header priority, accepted AIR, effect/capability semantics and AIR E0004 are preserved. Invalid-source diagnostics can change; no new code or reason. + +## Q-052 — Resource provenance through CFG parameters + +P6-7 rejection-twin work reproduced accepted source that returns the cancelled handle from an inner block, ends its lent borrow at that block's exit, then joins the renamed handle. Ordinary AIR `br` has the same defect: loans and creating scopes remain attached to the moved SSA value. Review also reproduced lost guard parents and shield order. These violate existing spec 04 §33–§34, §37.3 and §40; they are verifier bugs, not missing transfer semantics. + +**Resolved (DD-024):** resource relations follow simultaneous edge renaming, with a finite worklist covering later predecessors and backedges. Loans retain the creating spawn; tasks retain scope associations even when only the scope is passed. Guard parents and ordered shield relations survive handoff. Task/guard facts merge by union; shield stacks retain their existing exact join requirement. Existing codes E4302/E4101/E4301/E2102/E4305/E3002 apply. Valid correlated scope/task permutations and joins remain accepted. Runtime, source lowering and AIR format-0 meanings are unchanged; previously accepted violations now reject. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 43b531e..593d73f 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -303,3 +303,9 @@ Validation: units and Zig formatting pass; full conformance is 1,594/1,594, and DD-023 resolves Q-051: ordinary effect declarations validate the existing registry after signature types/from and before body lowering. Templates/static contracts replace incorrect E0006 with E7002; `name` and `effect` identify the atom. Declaration/parameter positions and prior signature/template check order remain. Registered atoms, flat effect sets, static-contract uniqueness, effect coverage, explicit capabilities and AIR E0004 remain unchanged. No new code/reason, syntax, feature, verifier/runtime, ownership/concurrency or evaluation input changes. Validation: units and Zig formatting pass; full conformance is 1,618/1,618, and all 24 new fixtures pass collection before every instruction. CLI integration passes 236 checks, including unused/package headers, diagnostic priority, formatter preservation, source/AIR execution, instantiation and independent AIR rejection. Existing generic/static-function/grammar suites pass 32/25/288 checks. Old/new comparison on 1,303 public sources (709 old lowerings) changes only the two corrected E0006 fixtures, preserving their primary positions and `name`; accepted AIR is byte-identical. Claude independently reviewed the change and ran units/fixtures and all 236 CLI checks. Bundle growth is recorded in docs/agent/README.md; P6-2 remains open. + +## P6-7 CFG resource-provenance correction (2026-10-08) + +Rejection-twin work exposed accepted source that ended a task loan after cancelled-handle transfer through a block parameter. DD-024 resolves Q-052: task loans/scopes, guard parents and shield order now follow simultaneous CFG transfers, with a fixed point for later predecessors and backedges. Existing concurrency invariants and diagnostic codes apply; interpreter behavior and valid source lowering are unchanged. This enforces existing AIR format-0 rules, with no new source concept, syntax or feature. + +Validation: units and Zig formatting pass; full conformance is 1,642/1,642. All 24 new AIR/source fixtures pass schedule stress and collection before every instruction. A counted 63-handle rotation test verifies convergence and retained spawn provenance. CLI integration passes 146 checks, including exact source/package/generic positions, three loan rejection twins and both correlated scope/task permutations; existing related-location and lifetime suites pass 349/188 checks. Old/new comparison changes zero diagnostics on 1,327 existing public sources and 338 AIR files, preserving all 715 old source lowerings. Claude wrote independent regressions and reviewed the implementation with additional loop/permutation/cancellation probes. Source bundle size is unchanged; AIR growth is recorded in docs/agent/README.md. The exhaustive rejection-twin inventory and P6-7 remain open. diff --git a/docs/spec/04-concurrency-and-atomics.md b/docs/spec/04-concurrency-and-atomics.md index 5a7cdce..04a02d2 100644 --- a/docs/spec/04-concurrency-and-atomics.md +++ b/docs/spec/04-concurrency-and-atomics.md @@ -506,6 +506,8 @@ Depends on `ownership`. **Function-bound.** A `scope` or `task` may be passed between blocks of the function that created it (as a block argument) and used by `task.*`. It may not be a function parameter, a return type, an aggregate member, or stored in heap or region memory; those uses belong to the reserved feature `task_transfer` (`E0006` reason `feature_not_declared`). Keeping handles in their function keeps loans intraprocedural (invariant 6). +Passing block arguments MUST preserve each task's creating scope and outstanding loans; the creating spawn remains diagnostic context (§34). Arguments are transferred simultaneously: renaming a scope also renames its association with tasks that remain live. Verification covers every incoming edge, including backedges; SSA renaming does not discharge an obligation. + **Result type.** `task` requires `T: Send`, and `T` must not transitively contain a borrow, a `scope` or a `task<…>`. A spawned function returning a borrow (for example one derived from a lent argument) belongs to the reserved feature `task_borrow_returns` (`E0006`): after `join`, whether the loan ends or continues as the returned borrow is deliberately left undefined in format 0. ### 33.2 Instructions @@ -696,6 +698,8 @@ cancelled(%t2: task): `shield` is linear, function-bound (§33.1) and `Local`. The stack of live shields is part of the verifier state and MUST be identical on every edge into a block (`E3002`); every shield is ended before `ret` (`E3002`). Shield depth is dynamic per task, so a function called inside a shield runs shielded. +Block-argument transfer preserves shield order. + ```text %a = task.shield.begin %b = task.shield.begin @@ -811,6 +815,8 @@ Decision record: RFC 0012. Depends on `cancellation`. `RwLock` is deferred (rese No fairness is promised (§32). There is no poisoning and no implicit unlock; an unconsumed guard is `E3002`. +Block-argument transfer preserves the association between a live guard and the mutex borrow through which it was obtained. + `mutex` is always linear and never copyable, whatever `T` is; `mutex.take` is the only way to dismantle it. It requires that no borrow of the mutex is live. A guard is a child of the `ref>` it was locked through (ending that borrow while the guard lives is `E2102`), and a task waiting in `mutex.lock` holds such a borrow, so no guard and no waiter can exist at `mutex.take`. Afterwards the mutex is dead, by the ordinary rules for a dismantled linear value (as after `own.take`): a further use is `E3001` and a further consumption `E2002`. ## 41. The critical-section rule diff --git a/src/verifier/borrow.zig b/src/verifier/borrow.zig index 6eec841..a1713ab 100644 --- a/src/verifier/borrow.zig +++ b/src/verifier/borrow.zig @@ -1,17 +1,16 @@ //! Borrow verification for frame storage (spec 08 §11). //! Reports E2101, E2102, E2105, E2106, E2107, E2108. //! -//! Every borrow value has static provenance fixed at its definition (root, -//! path, mode, parent). The only flow-sensitive state is the set of live -//! owned borrows. It must be identical on every edge into a block (§11.4), -//! so one walk over the reverse postorder decides each function. The walk -//! covers blocks reachable from the entry block; other blocks never execute. +//! Borrow definitions have static provenance. Live values must agree at joins. +//! Resource relations also follow block arguments; a monotone worklist solves +//! them before the diagnostic walk, including later predecessors/backedges. const std = @import("std"); const air = @import("../air.zig"); const verifier = @import("../verifier.zig"); const ssa = @import("ssa.zig"); const diag = @import("../diag.zig"); +const provenance = @import("provenance.zig"); const Context = verifier.Context; const ValueId = air.ValueId; @@ -30,16 +29,6 @@ const Seg = union(enum) { const Mode = enum { shared, exclusive }; -const Loan = struct { - task: ValueId, - borrow: ValueId, - root: ValueId, - path: []const Seg, - mode: Mode, - /// Diagnostic provenance only; never participates in borrow/liveness state. - spawn: air.Span, -}; - /// Why a resource is no longer live (spec 06 §6.3). const Dead = enum { none, closed, moved }; @@ -76,19 +65,22 @@ const Walker = struct { live: []bool, /// How a resource stopped being live, for diagnostics. dead: []Dead, - /// Borrows lent to tasks (spec 04 §34). A loan is active while its task - /// handle is live, so it is part of the per-path state through `live`. - loans: std.ArrayList(Loan) = .empty, - /// Scope of each task handle value. - task_scope: []?ValueId, - /// Number of shields live when each shield began (spec 04 §37.3). - shield_depth: []u32, - /// The `ref>` each guard was locked through (spec 04 §40). - guard_parent: []?ValueId, + facts: provenance.State = .{}, + /// First walk records definition/consumption events with relational + /// checks disabled. Its diagnostics are discarded, not published. + collecting: bool = false, + events: ?*std.ArrayList(provenance.Event) = null, + block: u32 = 0, index: u32 = 0, span: air.Span = .{ .line = 0, .col = 0 }, + fn event(w: *Walker, e: provenance.Event) !void { + if (w.collecting) { + if (w.events) |out| try out.append(w.c.arena, e); + } else try w.facts.apply(w.c.arena, e); + } + fn name(w: *Walker, v: ValueId) ![]const u8 { return w.c.valueName(w.f, v); } @@ -161,11 +153,13 @@ const Walker = struct { return; } // Borrows lent to live tasks are accessed concurrently (spec 04 §34). - for (w.loans.items) |l| { - if (!w.live[l.task] or l.root != root) continue; - if (mode == .shared and l.mode == .shared) continue; - if (!overlap(path, l.path)) continue; - try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.task }); + for (w.facts.items.items) |l| { + if (l.kind != .loan or !w.live[l.a]) continue; + const li = w.info[l.b] orelse continue; + if (li.root != root) continue; + if (mode == .shared and li.mode == .shared) continue; + if (!overlap(path, li.path)) continue; + try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.a }); return; } } @@ -236,6 +230,7 @@ const Walker = struct { try w.access(v, &.{}, .exclusive, null, v); w.live[v] = false; w.dead[v] = how; + try w.event(.{ .kill = v }); } }; @@ -303,7 +298,7 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void } } -fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { +fn walker(c: *Context, f: air.Function, types: []const air.Type) !Walker { var w: Walker = .{ .c = c, .f = f, @@ -311,13 +306,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { .info = try c.arena.alloc(?Info, f.values.len), .live = try c.arena.alloc(bool, f.values.len), .dead = try c.arena.alloc(Dead, f.values.len), - .task_scope = try c.arena.alloc(?ValueId, f.values.len), - .shield_depth = try c.arena.alloc(u32, f.values.len), - .guard_parent = try c.arena.alloc(?ValueId, f.values.len), }; - @memset(w.task_scope, null); - @memset(w.shield_depth, 0); - @memset(w.guard_parent, null); @memset(w.info, null); @memset(w.live, false); @memset(w.dead, .none); @@ -333,7 +322,40 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { if (c.module.isLinearType(p.ty)) w.live[p.value] = true; } + return w; +} + +fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { const dom = try ssa.dominators(c.arena, f); + // Most functions have no relational resources and retain the single walk. + var relational = false; + for (types) |t| switch (t) { + .task, .scope, .shield, .guard => { + relational = true; + break; + }, + else => {}, + }; + if (!relational) { + var w = try walker(c, f, types); + return walkFunction(&w, dom, null, null); + } + const events = try c.arena.alloc(std.ArrayList(provenance.Event), f.blocks.len); + for (events) |*list| list.* = .empty; + var collecting = c.*; + collecting.diags = .empty; + var first = try walker(&collecting, f, types); + first.collecting = true; + try walkFunction(&first, dom, null, events); + const facts = try solveProvenance(c.arena, f, types, dom, events, null); + var final = try walker(c, f, types); + try walkFunction(&final, dom, facts, null); +} + +fn walkFunction(w: *Walker, dom: ssa.Dominators, facts: ?[]provenance.State, events: ?[]std.ArrayList(provenance.Event)) !void { + const c = w.c; + const f = w.f; + const types = w.types; const entry_state = try c.arena.alloc(?[]bool, f.blocks.len); @memset(entry_state, null); entry_state[0] = try c.arena.dupe(bool, w.live); @@ -342,6 +364,8 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { var out: std.ArrayList(Edge) = .empty; for (dom.rpo) |b| { + if (events) |lists| w.events = &lists[b]; + if (facts) |entries| w.facts = try entries[b].clone(c.arena); @memcpy(w.live, entry_state[b].?); const blk = f.blocks[b]; // Linear block parameters own their argument from here on; the @@ -354,17 +378,21 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { for (blk.insts, 0..) |inst, ii| { w.index = @intCast(ii); w.span = inst.span; - try step(&w, inst); + if (inst.result) |v| if (w.isResource(v)) try w.event(.{ .kill = v }); + try step(w, inst); } + w.events = null; // Propagate along every edge; branch arguments of resource type are // moved on their own edge only (§11.4, spec 06 §6.2). out.clearRetainingCapacity(); try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena); const base = try c.arena.dupe(bool, w.live); const base_dead = try c.arena.dupe(Dead, w.dead); + const base_facts = try w.facts.clone(c.arena); for (out.items) |e| { @memcpy(w.live, base); @memcpy(w.dead, base_dead); + w.facts = try base_facts.clone(c.arena); for (e.args) |a| if (c.module.isLinearType(types[a])) try w.consume(a, .moved); // A linear parameter of the target that is still live on this // edge would be overwritten: that instance leaks. Parameters are @@ -387,10 +415,93 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { }; } } else entry_state[e.target] = try c.arena.dupe(bool, w.live); + if (facts) |entries| { + const incoming = try edgeProvenance(c.arena, base_facts, f, types, dom, e); + if (!reported_join[e.target]) if (entries[e.target].differentShield(incoming)) |shield| { + reported_join[e.target] = true; + try c.report("E3002", f.blocks[e.target].span, "shield order differs between edges into this block", &.{ + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } }, + .{ .name = "resource", .value = .{ .str = try c.valueName(f, shield) } }, + }); + }; + } } } } +/// All linear arguments move simultaneously, including the scope position +/// of facts whose task itself is not passed. Old target-parameter instances +/// are overwritten; implicit outcome definitions were recorded as events. +fn edgeProvenance(arena: std.mem.Allocator, base: provenance.State, f: air.Function, types: []const air.Type, dom: ssa.Dominators, e: Edge) !provenance.State { + var out: provenance.State = .{}; + for (base.items.items) |old| { + var fact = old; + fact.a = edgeValue(old.a, f, types, dom, e) orelse continue; + fact.b = edgeValue(old.b, f, types, dom, e) orelse continue; + _ = try out.add(arena, fact); + } + return out; +} + +fn edgeValue(v: ValueId, f: air.Function, types: []const air.Type, dom: ssa.Dominators, e: Edge) ?ValueId { + for (e.args, 0..) |arg, i| if (arg == v and types[arg].isLinear()) return f.blocks[e.target].params[i].value; + // Explicit targets overwrite any older instance of their parameters. + if (e.args.len != 0) for (f.blocks[e.target].params) |p| if (p.value == v) return null; + return switch (f.values[v].def) { + .param => v, + .block_param => |d| if (dom.dominates(d.block, e.target)) v else null, + .inst => |d| if (dom.dominates(d.block, e.target)) v else null, + .none => unreachable, + }; +} + +const ProvenanceStats = struct { + visits: usize = 0, + facts: usize = 0, +}; + +/// A finite monotone lattice of resource relations and loan origins. Events +/// depend only on definitions and the collecting live-value transfer. Final +/// error recovery may close extra values; checks filter those dead subjects, +/// so collecting is conservative. Sparse sets retain insertion order; union +/// does not impose a new equality rule on task/guard origins. +fn solveProvenance(arena: std.mem.Allocator, f: air.Function, types: []const air.Type, dom: ssa.Dominators, events: []std.ArrayList(provenance.Event), stats: ?*ProvenanceStats) ![]provenance.State { + const entries = try arena.alloc(provenance.State, f.blocks.len); + for (entries) |*s| s.* = .{}; + const visited = try arena.alloc(bool, f.blocks.len); + @memset(visited, false); + const queued = try arena.alloc(bool, f.blocks.len); + @memset(queued, false); + var queue: std.ArrayList(u32) = .empty; + try queue.append(arena, 0); + queued[0] = true; + visited[0] = true; + var pos: usize = 0; + var out: std.ArrayList(Edge) = .empty; + while (pos < queue.items.len) : (pos += 1) { + const b = queue.items[pos]; + if (stats) |s| s.visits += 1; + queued[b] = false; + var state = try entries[b].clone(arena); + for (events[b].items) |event| try state.apply(arena, event); + out.clearRetainingCapacity(); + const block = f.blocks[b]; + try edges(block.insts[block.insts.len - 1].op, &out, arena); + for (out.items) |e| { + const incoming = try edgeProvenance(arena, state, f, types, dom, e); + const changed = try entries[e.target].merge(arena, incoming); + if (stats) |s| s.facts += incoming.items.items.len; + if ((!visited[e.target] or changed) and !queued[e.target]) { + try queue.append(arena, e.target); + queued[e.target] = true; + } + visited[e.target] = true; + } + } + return entries; +} + fn step(w: *Walker, inst: air.Inst) !void { const f = w.f; switch (inst.op) { @@ -432,11 +543,11 @@ fn step(w: *Walker, inst: air.Inst) !void { if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null); // Ended even when rejected, so one mistake yields one diagnostic. defer w.live[v] = false; - for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) { - return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task }, l.spawn); + for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and (l.b == v or w.isAncestor(v, l.b))) { + return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.a }, l.spawn); }; - for (w.live, 0..) |is_live, g| if (is_live and w.guard_parent[g] != null and w.isAncestor(v, w.guard_parent[g].?)) { - return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", @intCast(g) }); + for (w.facts.items.items) |g| if (g.kind == .guard and w.live[g.a] and w.isAncestor(v, g.b)) { + return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", g.a }); }; for (w.live, 0..) |is_live, cv| { if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) { @@ -508,14 +619,14 @@ fn step(w: *Walker, inst: air.Inst) !void { .task_spawn => |x| { try noWaitUnderLock(w, "task.spawn"); const t = inst.result.?; - w.task_scope[t] = x.scope; + try w.event(.{ .add = .{ .kind = .scope, .a = t, .b = x.scope } }); for (x.args) |a| { if (w.types[a].isBorrow()) { if (!try w.usable(a)) continue; const ai = w.info[a].?; // The loan must not conflict with live borrows or loans. try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow"); - try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode, .spawn = inst.span }); + try w.event(.{ .add = .{ .kind = .loan, .a = t, .b = a, .spawn = inst.span } }); } else if (w.isResource(a)) try w.consume(a, .moved); } w.live[t] = true; @@ -530,11 +641,15 @@ fn step(w: *Walker, inst: air.Inst) !void { }, .task_cancel => |t| _ = try w.resourceUsable(t), .task_scope_end => |s| { - for (w.live, 0..) |is_live, v| { - if (is_live and w.task_scope[v] != null and w.task_scope[v].? == s) { - try w.report("E4301", "scope ends while a task spawned from it is not joined", @intCast(v), .{ "scope", s }); - w.live[v] = false; // reported once, in preference to E3002 - } + // Copy the selected handles before killing their facts. + var children: std.ArrayList(ValueId) = .empty; + for (w.facts.items.items) |fact| if (fact.kind == .scope and fact.b == s and w.live[fact.a]) { + if (std.mem.indexOfScalar(ValueId, children.items, fact.a) == null) try children.append(w.c.arena, fact.a); + }; + for (children.items) |v| { + try w.report("E4301", "scope ends while a task spawned from it is not joined", v, .{ "scope", s }); + w.live[v] = false; // prefer E4301 to E3002 + try w.event(.{ .kill = v }); } try w.consume(s, .closed); }, @@ -575,28 +690,20 @@ fn step(w: *Walker, inst: air.Inst) !void { const back = w.f.blocks[x.cancelled].params[0].value; // On `cancelled` the same task comes back: its scope and loans // move to the new handle value (spec 04 §37.3). - w.task_scope[back] = w.task_scope[t]; - const n = w.loans.items.len; - for (0..n) |i| { - const l = w.loans.items[i]; - if (l.task == t) { - var transferred = l; - transferred.task = back; - try w.loans.append(w.c.arena, transferred); - } - } + try w.event(.{ .kill = back }); + try w.event(.{ .rename = .{ .from = t, .to = back } }); try w.consume(t, .closed); }, .task_shield_begin => { const r = inst.result.?; - var depth: u32 = 0; - for (w.live, 0..) |is_live, v| depth += @intFromBool(is_live and w.types[v] == .shield); - w.shield_depth[r] = depth; + for (w.live, 0..) |is_live, v| if (is_live and w.types[v] == .shield) { + try w.event(.{ .add = .{ .kind = .inner, .a = r, .b = @intCast(v) } }); + }; w.live[r] = true; }, .task_shield_end => |sh| { - if (w.live[sh]) for (w.live, 0..) |is_live, v| if (is_live and w.types[v] == .shield and w.shield_depth[v] > w.shield_depth[sh]) { - try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", @intCast(v) }); + if (w.live[sh]) for (w.facts.items.items) |fact| if (fact.kind == .inner and fact.b == sh and w.live[fact.a]) { + try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", fact.a }); break; }; try w.consume(sh, .closed); @@ -640,7 +747,9 @@ fn step(w: *Walker, inst: air.Inst) !void { .mutex_lock => |x| { try noWaitUnderLock(w, "mutex.lock"); try lendArgs(w, &.{x.mutex}); - w.guard_parent[w.f.blocks[x.ok].params[0].value] = x.mutex; + const g = w.f.blocks[x.ok].params[0].value; + try w.event(.{ .kill = g }); + try w.event(.{ .add = .{ .kind = .guard, .a = g, .b = x.mutex } }); }, .mutex_borrow => |g| { const r = inst.result.?; @@ -659,6 +768,7 @@ fn step(w: *Walker, inst: air.Inst) !void { }; w.live[g] = false; w.dead[g] = .closed; + try w.event(.{ .kill = g }); }, // Graphs (spec 03 §22–§24). An access is a child borrow of the // container borrow; a `mut` child is exclusive for the whole island. @@ -692,8 +802,8 @@ fn step(w: *Walker, inst: air.Inst) !void { /// Taking a mutex or an atomic cell while a borrow of it is lent to a live /// task races with that task: `E4101` rather than `E2101` (spec 04 §28, §40). fn takeLent(w: *Walker, v: ValueId) !bool { - for (w.loans.items) |l| if (w.live[l.task] and l.root == v) { - try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.task }); + for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and w.info[l.b] != null and w.info[l.b].?.root == v) { + try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.a }); // Consumed all the same, so the mistake is not reported again as a leak. w.live[v] = false; w.dead[v] = .closed; @@ -846,3 +956,47 @@ test "call results keep their source alive; mut arguments do not alias" { const two = "fn @g(%a: mut, %b: ref) -> void\neffects []\nentry:\n ret\n"; try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n" ++ local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n call @g(%m, %r)\n borrow.end %r\n borrow.end %m\n ret\n" ++ two, &.{"E2101"}); } + +test "task provenance rotation reaches every header parameter with bounded visits" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const count = 63; // Below the existing 64-parameter limit. + var source: std.Io.Writer.Allocating = .init(a); + const out = &source.writer; + try out.writeAll("module rotation\nair 0\nlang 0.1\nfeatures [cancellation, effects, ownership, tasks]\nfn @main() -> void\neffects [task.spawn]\nentry:\n %x = local.alloc u8\n local.zero %x\n %r = borrow.ref %x\n %s = task.scope.begin\n %t0 = task.spawn %s, @read(%r)\n"); + for (1..count) |i| try out.print(" %t{d} = task.spawn %s, @zero()\n", .{i}); + try out.writeAll(" br @head("); + for (0..count) |i| try out.print("{s}%t{d}", .{ if (i == 0) "" else ", ", i }); + try out.writeAll(")\nhead("); + for (0..count) |i| try out.print("{s}%p{d}: task", .{ if (i == 0) "" else ", ", i }); + try out.writeAll("):\n br @head("); + for (0..count) |i| try out.print("{s}%p{d}", .{ if (i == 0) "" else ", ", (i + 1) % count }); + try out.writeAll(")\nfn @read(%p: ref) -> u8\neffects []\nentry:\n %v = load %p\n ret %v\nfn @zero() -> u8\neffects []\nentry:\n %v = const.u8 0\n ret %v\n"); + const parsed = try air.parse.parse(a, "rotation.air", source.written()); + try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len); + var c: Context = .{ .arena = a, .file = "rotation.air", .module = parsed.module.? }; + try verifier.cfg.check(&c); + try ssa.check(&c); + try verifier.types.check(&c); + try std.testing.expectEqual(@as(usize, 0), c.diags.items.len); + const f = c.module.functions[0]; + const types = c.value_types[0]; + const dom = try ssa.dominators(a, f); + const events = try a.alloc(std.ArrayList(provenance.Event), f.blocks.len); + for (events) |*e| e.* = .empty; + var w = try walker(&c, f, types); + w.collecting = true; + try walkFunction(&w, dom, null, events); + try std.testing.expectEqual(@as(usize, 0), c.diags.items.len); + var stats: ProvenanceStats = .{}; + const entries = try solveProvenance(a, f, types, dom, events, &stats); + var loans: usize = 0; + for (entries[1].items.items) |fact| if (fact.kind == .loan) { + loans += 1; + try std.testing.expectEqual(@as(u32, 12), fact.spawn.line); + }; + try std.testing.expectEqual(@as(usize, count), loans); + try std.testing.expect(stats.visits <= count + 2); + try std.testing.expect(stats.facts <= 2 * count * (count + 2)); +} diff --git a/src/verifier/provenance.zig b/src/verifier/provenance.zig new file mode 100644 index 0000000..6f74cd1 --- /dev/null +++ b/src/verifier/provenance.zig @@ -0,0 +1,100 @@ +//! Function-local resource relations, independent of SSA spelling. +//! Facts join by union; edge renaming is simultaneous in both positions. +//! Shield order additionally has an exact-state join rule (spec 04 §37.3). +const std = @import("std"); +const air = @import("../air.zig"); + +pub const Kind = enum { loan, scope, guard, inner }; +pub const Fact = struct { + kind: Kind, + a: air.ValueId, + b: air.ValueId, + // Meaningful only for loans. Never changes their transfer semantics. + spawn: air.Span = .{ .line = 0, .col = 0 }, +}; + +pub const Event = union(enum) { + add: Fact, + kill: air.ValueId, + // The cancelled join replaces a task handle without ending its loans. + rename: struct { from: air.ValueId, to: air.ValueId }, +}; + +pub const State = struct { + items: std.ArrayList(Fact) = .empty, + set: std.AutoHashMapUnmanaged(Fact, void) = .empty, + + pub fn add(s: *State, arena: std.mem.Allocator, fact: Fact) !bool { + const r = try s.set.getOrPut(arena, fact); + if (r.found_existing) return false; + try s.items.append(arena, fact); + return true; + } + + pub fn merge(s: *State, arena: std.mem.Allocator, other: State) !bool { + var changed = false; + for (other.items.items) |fact| changed = (try s.add(arena, fact)) or changed; + return changed; + } + + pub fn clone(s: State, arena: std.mem.Allocator) !State { + var out: State = .{}; + _ = try out.merge(arena, s); + return out; + } + + pub fn kill(s: *State, v: air.ValueId) void { + var n: usize = 0; + for (s.items.items) |fact| { + if (fact.a == v or fact.b == v) { + _ = s.set.remove(fact); + } else { + s.items.items[n] = fact; + n += 1; + } + } + s.items.shrinkRetainingCapacity(n); + } + + pub fn apply(s: *State, arena: std.mem.Allocator, event: Event) !void { + switch (event) { + .add => |f| _ = try s.add(arena, f), + .kill => |v| s.kill(v), + .rename => |r| { + var out: State = .{}; + for (s.items.items) |old| { + var f = old; + if (f.a == r.from) f.a = r.to; + if (f.b == r.from) f.b = r.to; + _ = try out.add(arena, f); + } + s.* = out; + }, + } + } + + pub fn sameShields(a: State, b: State) bool { + return a.differentShield(b) == null; + } + + pub fn differentShield(a: State, b: State) ?air.ValueId { + for (a.items.items) |f| if (f.kind == .inner and !b.set.contains(f)) return f.a; + for (b.items.items) |f| if (f.kind == .inner and !a.set.contains(f)) return f.a; + return null; + } +}; + +test "relations retain loan origin, join once and remove both endpoints" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var s: State = .{}; + const loan: Fact = .{ .kind = .loan, .a = 1, .b = 2, .spawn = .{ .line = 7, .col = 3 } }; + try std.testing.expect(try s.add(a, loan)); + try std.testing.expect(!try s.add(a, loan)); + try s.apply(a, .{ .rename = .{ .from = 1, .to = 4 } }); + try std.testing.expectEqual(@as(air.ValueId, 4), s.items.items[0].a); + try std.testing.expectEqual(loan.spawn, s.items.items[0].spawn); + s.kill(2); + try std.testing.expectEqual(@as(usize, 0), s.items.items.len); +} diff --git a/tests/conformance/phase3/reject/cfg_provenance_cancel_arg.air b/tests/conformance/phase3/reject/cfg_provenance_cancel_arg.air new file mode 100644 index 0000000..782f950 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_cancel_arg.air @@ -0,0 +1,41 @@ +; The cancelled handle of task.join.cancel passed through an ordinary block argument keeps its loans. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34, §37 +module test.cfg_provenance_cancel_arg +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 + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + task.join.cancel %t, ok -> @joined, cancelled -> @cancelled +joined(%v: u8): + task.scope.end %sc + borrow.end %r + ret %v +cancelled(%t1: task): + br @handle(%t1) +handle(%t2: task): + borrow.end %r + %v2 = task.join %t2 + task.scope.end %sc + ret %v2 + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_guard_parent.air b/tests/conformance/phase3/reject/cfg_provenance_guard_parent.air new file mode 100644 index 0000000..9702182 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_guard_parent.air @@ -0,0 +1,27 @@ +; A guard passed through a block argument still depends on the mutex borrow it was locked through; ending that borrow while the guard is live is rejected. +; expect: reject E2102 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §40 +module test.cfg_provenance_guard_parent +air 0 +lang 0.1 +features [cancellation, effects, ownership, sync, tasks] + +fn @main() -> u64 +effects [task.wait] +entry: + %z = const.u64 0 + %m = mutex.make %z + %mr = borrow.ref %m + mutex.lock %mr, ok -> @locked, cancelled -> @out +locked(%g: guard): + br @next(%g) +next(%g2: guard): + borrow.end %mr + mutex.unlock %g2 + %v = mutex.take %m + ret %v +out: + borrow.end %mr + %w = mutex.take %m + ret %w diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_access.air b/tests/conformance/phase3/reject/cfg_provenance_loan_access.air new file mode 100644 index 0000000..998542a --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_access.air @@ -0,0 +1,37 @@ +; Parent store through the lent exclusive borrow races after a handle handoff. +; expect: reject E4101 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_access +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.mut %x + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + br @next(%t) +next(%t2: task): + %one = const.u8 1 + store %r, %one + %v = task.join %t2 + borrow.end %r + task.scope.end %sc + ret %v + +fn @rd(%p: mut) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_backedge.air b/tests/conformance/phase3/reject/cfg_provenance_loan_backedge.air new file mode 100644 index 0000000..5609928 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_backedge.air @@ -0,0 +1,42 @@ +; The loop body lends the borrow to a new task and passes it back to the header; the exit sees that handle through the header parameter, so ending the borrow before its join is rejected. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_backedge +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 + %sc = task.scope.begin + %t0 = task.spawn %sc, @zero() + br @head(%t0) +head(%t: task): + %c = const.bool false + cbr %c, @body(%t), @exit(%t) +body(%tb: task): + %old = task.join %tb + %t1 = task.spawn %sc, @rd(%r) + br @head(%t1) +exit(%te: task): + borrow.end %r + %v = task.join %te + task.scope.end %sc + ret %v + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_br.air b/tests/conformance/phase3/reject/cfg_provenance_loan_br.air new file mode 100644 index 0000000..fc93f7d --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_br.air @@ -0,0 +1,35 @@ +; A task handle passed through an ordinary block argument keeps its loans: ending the lent borrow before the join is rejected. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_br +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 + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + br @next(%t) +next(%t2: task): + borrow.end %r + %v = task.join %t2 + task.scope.end %sc + ret %v + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_cbr.air b/tests/conformance/phase3/reject/cfg_provenance_loan_cbr.air new file mode 100644 index 0000000..17ac792 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_cbr.air @@ -0,0 +1,41 @@ +; Both cbr targets receive the lent task; ending the borrow before the join on one target is rejected. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_cbr +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 + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + %c = const.bool true + cbr %c, @early(%t), @late(%t) +early(%a: task): + borrow.end %r + %va = task.join %a + task.scope.end %sc + ret %va +late(%b: task): + %vb = task.join %b + borrow.end %r + task.scope.end %sc + ret %vb + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_join.air b/tests/conformance/phase3/reject/cfg_provenance_loan_join.air new file mode 100644 index 0000000..d0700df --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_join.air @@ -0,0 +1,41 @@ +; One predecessor lends the borrow to its task and the other does not; after the join the handle may hold the loan, so ending the borrow first is rejected. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_join +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 + %sc = task.scope.begin + %c = const.bool true + cbr %c, @lend(), @plain() +lend: + %t1 = task.spawn %sc, @rd(%r) + br @joined(%t1) +plain: + %t2 = task.spawn %sc, @zero() + br @joined(%t2) +joined(%t: task): + borrow.end %r + %v = task.join %t + task.scope.end %sc + ret %v + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_loan_switch.air b/tests/conformance/phase3/reject/cfg_provenance_loan_switch.air new file mode 100644 index 0000000..e838e27 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_loan_switch.air @@ -0,0 +1,41 @@ +; An integer switch hands the lent task to its targets; ending the borrow before the join on the default target is rejected. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_switch +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 + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + %k = const.u8 7 + switch.u8 %k, 0 -> @zero_case(%t), default -> @other(%t) +zero_case(%a: task): + %va = task.join %a + borrow.end %r + task.scope.end %sc + ret %va +other(%b: task): + borrow.end %r + %vb = task.join %b + task.scope.end %sc + ret %vb + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_scope_alone.air b/tests/conformance/phase3/reject/cfg_provenance_scope_alone.air new file mode 100644 index 0000000..935a542 --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_scope_alone.air @@ -0,0 +1,31 @@ +; Only the scope is passed through a block argument; its task is still unjoined when the renamed scope ends. +; expect: reject E4301 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §33 +module test.cfg_provenance_scope_alone +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn, task.wait] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @zero() + br @next(%sc) +next(%s2: scope): + task.scope.end %s2 + %v = const.u8 0 + ret %v + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_scope_task.air b/tests/conformance/phase3/reject/cfg_provenance_scope_task.air new file mode 100644 index 0000000..b4e80ca --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_scope_task.air @@ -0,0 +1,31 @@ +; The scope and its task are passed together through block arguments; the renamed scope ends while the renamed task is unjoined. +; expect: reject E4301 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §33 +module test.cfg_provenance_scope_task +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn, task.wait] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @zero() + br @next(%sc, %t) +next(%s2: scope, %t2: task): + task.scope.end %s2 + %v = const.u8 0 + ret %v + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/reject/cfg_provenance_shield_order.air b/tests/conformance/phase3/reject/cfg_provenance_shield_order.air new file mode 100644 index 0000000..922303c --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_shield_order.air @@ -0,0 +1,19 @@ +; Shields passed through block arguments keep their nesting: ending the outer shield first is rejected. +; expect: reject E4305 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §37.3 +module test.cfg_provenance_shield_order +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> void +effects [] +entry: + %a = task.shield.begin + %b = task.shield.begin + br @next(%a, %b) +next(%outer: shield, %inner: shield): + task.shield.end %outer + task.shield.end %inner + ret diff --git a/tests/conformance/phase3/reject/cfg_provenance_shield_stack_join.air b/tests/conformance/phase3/reject/cfg_provenance_shield_stack_join.air new file mode 100644 index 0000000..47840fd --- /dev/null +++ b/tests/conformance/phase3/reject/cfg_provenance_shield_stack_join.air @@ -0,0 +1,21 @@ +; Incoming stacks disagree; ending a first also violates the b-inside-a path. +; The two edges into a block pass the live shields in opposite nesting order, so the shield stack differs between edges (spec 04 §37.3). +; expect: reject E3002 E4305 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §37.3 +module test.cfg_provenance_shield_stack_join +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> void +effects [] +entry: + %a = task.shield.begin + %b = task.shield.begin + %c = const.bool true + cbr %c, @joined(%a, %b), @joined(%b, %a) +joined(%x: shield, %y: shield): + task.shield.end %y + task.shield.end %x + ret diff --git a/tests/conformance/phase3/run/cfg_provenance_cancel_arg.air b/tests/conformance/phase3/run/cfg_provenance_cancel_arg.air new file mode 100644 index 0000000..7a2a533 --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_cancel_arg.air @@ -0,0 +1,38 @@ +; The cancelled handle of task.join.cancel may travel through an ordinary block argument; joining it before ending the lent borrow is valid. +; expect: run +; schedules: 20 +; result: 5 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §37 +module test.cfg_provenance_cancel_arg +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn, task.wait] +entry: + %x = local.alloc u8 + %five = const.u8 5 + local.store %x, %five + %r = borrow.ref %x + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + task.join.cancel %t, ok -> @joined, cancelled -> @cancelled +joined(%v: u8): + task.scope.end %sc + borrow.end %r + ret %v +cancelled(%t1: task): + br @handle(%t1) +handle(%t2: task): + %v2 = task.join %t2 + task.scope.end %sc + borrow.end %r + ret %v2 + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v diff --git a/tests/conformance/phase3/run/cfg_provenance_correlated_scopes.air b/tests/conformance/phase3/run/cfg_provenance_correlated_scopes.air new file mode 100644 index 0000000..e721e6d --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_correlated_scopes.air @@ -0,0 +1,41 @@ +; Two scopes and their tasks are permuted together on the two edges into a block; each renamed task belongs to the renamed scope beside it, so joining and ending them pairwise is valid. +; expect: run +; schedules: 20 +; result: 12 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §33 +module test.cfg_provenance_correlated_scopes +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn, task.wait] +entry: + %s1 = task.scope.begin + %s2 = task.scope.begin + %t1 = task.spawn %s1, @one() + %t2 = task.spawn %s2, @two() + %c = const.bool true + cbr %c, @next(%s1, %s2, %t1, %t2), @next(%s2, %s1, %t2, %t1) +next(%pa: scope, %pb: scope, %ta: task, %tb: task): + %va = task.join %ta + task.scope.end %pa + %vb = task.join %tb + task.scope.end %pb + %ten = const.u8 10 + %hi = mul.checked.u8 %va, %ten + %r = add.checked.u8 %hi, %vb + ret %r + +fn @one() -> u8 +effects [] +entry: + %v = const.u8 1 + ret %v + +fn @two() -> u8 +effects [] +entry: + %v = const.u8 2 + ret %v diff --git a/tests/conformance/phase3/run/cfg_provenance_guard_handoff.air b/tests/conformance/phase3/run/cfg_provenance_guard_handoff.air new file mode 100644 index 0000000..a3ea056 --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_guard_handoff.air @@ -0,0 +1,33 @@ +; A guard may be passed through a block argument; borrowing through it, unlocking and only then ending the mutex borrow is valid. +; expect: run +; schedules: 20 +; result: 7 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §40 +module test.cfg_provenance_guard_handoff +air 0 +lang 0.1 +features [cancellation, effects, ownership, sync, tasks] + +fn @main() -> u64 +effects [task.wait] +entry: + %z = const.u64 0 + %m = mutex.make %z + %mr = borrow.ref %m + mutex.lock %mr, ok -> @locked, cancelled -> @out +locked(%g: guard): + br @next(%g) +next(%g2: guard): + %p = mutex.borrow %g2 + %seven = const.u64 7 + store %p, %seven + borrow.end %p + mutex.unlock %g2 + borrow.end %mr + %v = mutex.take %m + ret %v +out: + borrow.end %mr + %w = mutex.take %m + ret %w diff --git a/tests/conformance/phase3/run/cfg_provenance_loan_returned.air b/tests/conformance/phase3/run/cfg_provenance_loan_returned.air new file mode 100644 index 0000000..82f6a89 --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_loan_returned.air @@ -0,0 +1,39 @@ +; Joining the renamed handle returns its exclusive loan before parent reuse. +; expect: run +; schedules: 20 +; result: 0 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_loan_returned +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.mut %x + %sc = task.scope.begin + %t = task.spawn %sc, @rd(%r) + br @next(%t) +next(%t2: task): + %v = task.join %t2 + %one = const.u8 1 + store %r, %one + borrow.end %r + task.scope.end %sc + ret %v + +fn @rd(%p: mut) -> u8 +effects [] +entry: + %v = load %p + ret %v + +fn @zero() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z diff --git a/tests/conformance/phase3/run/cfg_provenance_shield_handoff.air b/tests/conformance/phase3/run/cfg_provenance_shield_handoff.air new file mode 100644 index 0000000..b3c5a22 --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_shield_handoff.air @@ -0,0 +1,22 @@ +; Shields may be passed through block arguments and ended innermost first. +; expect: run +; schedules: 20 +; result: 4 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §37.3 +module test.cfg_provenance_shield_handoff +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [] +entry: + %a = task.shield.begin + %b = task.shield.begin + br @next(%a, %b) +next(%outer: shield, %inner: shield): + task.shield.end %inner + task.shield.end %outer + %v = const.u8 4 + ret %v diff --git a/tests/conformance/phase3/run/cfg_provenance_task_loop.air b/tests/conformance/phase3/run/cfg_provenance_task_loop.air new file mode 100644 index 0000000..9c6c8fd --- /dev/null +++ b/tests/conformance/phase3/run/cfg_provenance_task_loop.air @@ -0,0 +1,42 @@ +; A loop lends a borrow to a new task each iteration and joins it at the header; the borrow ends only after the last join. +; expect: run +; schedules: 20 +; result: 3 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance_task_loop +air 0 +lang 0.1 +features [cancellation, effects, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn, task.wait] +entry: + %x = local.alloc u8 + %one = const.u8 1 + local.store %x, %one + %r = borrow.ref %x + %sc = task.scope.begin + %t0 = task.spawn %sc, @rd(%r) + %zero = const.u8 0 + br @head(%t0, %zero, %zero) +head(%t: task, %acc: u8, %i: u8): + %v = task.join %t + %acc2 = add.checked.u8 %acc, %v + %i2 = add.checked.u8 %i, %one + %three = const.u8 3 + %more = lt.u8 %i2, %three + cbr %more, @body(%acc2, %i2), @exit(%acc2) +body(%a: u8, %n: u8): + %t1 = task.spawn %sc, @rd(%r) + br @head(%t1, %a, %n) +exit(%total: u8): + task.scope.end %sc + borrow.end %r + ret %total + +fn @rd(%p: ref) -> u8 +effects [] +entry: + %v = load %p + ret %v diff --git a/tests/conformance/source/cfg_provenance/cancel_join_keeps_loans.aji b/tests/conformance/source/cfg_provenance/cancel_join_keeps_loans.aji new file mode 100644 index 0000000..3fcdf59 --- /dev/null +++ b/tests/conformance/source/cfg_provenance/cancel_join_keeps_loans.aji @@ -0,0 +1,27 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §37 +// AIR twin: phase3/reject/cancel_join_keeps_loans.air +module test.twins.cancel_join_keeps_loans + +fn work(p: ref) -> u8 effects [] { + return *p; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + let t = { + ref part = data; // diagnostic here + let t = task.spawn(sc, work, part); // task spawn here + match task.join_cancel(move t) { + ok(n) => { + return n; + } cancelled(t) => { + move t + } + } + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/cfg_provenance/cancel_join_twice_keeps_spawn.aji b/tests/conformance/source/cfg_provenance/cancel_join_twice_keeps_spawn.aji new file mode 100644 index 0000000..1521ed8 --- /dev/null +++ b/tests/conformance/source/cfg_provenance/cancel_join_twice_keeps_spawn.aji @@ -0,0 +1,33 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §37 +// AIR twin: phase3/reject/cancel_join_twice_keeps_spawn.air +module test.twins.cancel_join_twice_keeps_spawn + +fn work(p: ref) -> u8 effects [] { + return *p; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + let t = { + ref part = data; // diagnostic here + let t = task.spawn(sc, work, part); // task spawn here + match task.join_cancel(move t) { + ok(n) => { + return n; + } cancelled(t) => { + match task.join_cancel(move t) { + ok(n) => { + return n; + } cancelled(t) => { + move t + } + } + } + } + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/cfg_provenance/cancel_task_block.aji b/tests/conformance/source/cfg_provenance/cancel_task_block.aji new file mode 100644 index 0000000..7e5916d --- /dev/null +++ b/tests/conformance/source/cfg_provenance/cancel_task_block.aji @@ -0,0 +1,28 @@ +// expect: run +// schedules: 20 +// result: 7 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance.cancel_task_block + +fn read(p: ref) -> u8 effects [] { + return *p; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = 7u8; + ref part = data; + scope sc { + let t = { + let child = task.spawn(sc, read, part); + match task.join_cancel(move child) { + ok(n) => { + return n; + } cancelled(back) => { + move back + } + } + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/cfg_provenance/task_block.aji b/tests/conformance/source/cfg_provenance/task_block.aji new file mode 100644 index 0000000..afe0bc0 --- /dev/null +++ b/tests/conformance/source/cfg_provenance/task_block.aji @@ -0,0 +1,22 @@ +// expect: run +// schedules: 20 +// result: 7 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance.task_block + +fn read(p: ref) -> u8 effects [] { + return *p; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = 7u8; + ref part = data; + scope sc { + let t = { + let child = task.spawn(sc, read, part); + move child + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/cfg_provenance/task_branch.aji b/tests/conformance/source/cfg_provenance/task_branch.aji new file mode 100644 index 0000000..8a4d4eb --- /dev/null +++ b/tests/conformance/source/cfg_provenance/task_branch.aji @@ -0,0 +1,23 @@ +// expect: run +// schedules: 20 +// result: 7 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34 +module test.cfg_provenance.task_branch + +fn read(p: ref) -> u8 effects [] { + return *p; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = 7u8; + ref part = data; + scope sc { + let t = if true { + task.spawn(sc, read, part) + } else { + task.spawn(sc, read, part) + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/cfg_provenance/tasks_end_lent_borrow.aji b/tests/conformance/source/cfg_provenance/tasks_end_lent_borrow.aji new file mode 100644 index 0000000..6d774ba --- /dev/null +++ b/tests/conformance/source/cfg_provenance/tasks_end_lent_borrow.aji @@ -0,0 +1,20 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34 +// AIR twin: phase3/reject/tasks_end_lent_borrow.air +module test.twins.tasks_end_lent_borrow + +fn work(p: mut) -> u64 effects [] { + return *p; +} + +fn main() -> u64 effects [task.spawn] { + var data: u64 = zero; + scope sc { + let t = { + mut part = data; // diagnostic here + task.spawn(sc, work, part) // task spawn here + }; + return task.join(move t); + } +} diff --git a/tests/hosted/source_cfg_provenance.py b/tests/hosted/source_cfg_provenance.py new file mode 100644 index 0000000..5728887 --- /dev/null +++ b/tests/hosted/source_cfg_provenance.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Resource handoff, exact loan origins and source/package/AIR diagnostics.""" +from collections import Counter +import json +from pathlib import Path +import re +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / 'zig-out/bin/aji' +CORPUS = REPO / 'tests/conformance' +checks = 0 + + +def records(*args, code=0): + global checks + result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True) + assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr) + checks += 1 + def unique(pairs): + out = {} + for key, value in pairs: + assert key not in out, ('duplicate diagnostic field', key) + out[key] = value + return out + return [json.loads(line, object_pairs_hook=unique) for line in result.stdout.splitlines()] + + +def lower(*args): + global checks + result = subprocess.run([str(AJI), 'lower', *map(str, args)], capture_output=True, text=True) + assert result.returncode == 0, result + checks += 1 + return result.stdout + + +def marker(source, text, token): + lines = [(i + 1, line) for i, line in enumerate(source.splitlines()) if text in line] + assert len(lines) == 1, lines + line, contents = lines[0] + return line, contents.index(token) + 1 + + +def rejection(root, path, *args, file=None): + source = path.read_text() + expected = marker(source, '// diagnostic here', 'part') + # Binding diagnostics use the ref/mut keyword, not the bound name. + line = source.splitlines()[expected[0] - 1] + expected = expected[0], len(line) - len(line.lstrip()) + 1 + spawn = marker(source, '// task spawn here', 'task.spawn') + ds = records('check', *args, code=1) + assert len(ds) == 1 and ds[0]['code'] == 'E4302', ds + d = ds[0] + assert (d['file'], d['line'], d['col']) == (file or str(path), *expected), d + related, = d['related_locations'] + assert (related['file'], related['line'], related['col']) == (file or str(path), *spawn), related + assert related['role'] == 'task_spawn' and related['value'] == d['task'], d + for command in ('run', 'report', 'explore'): + assert records(command, *args, code=1) == ds + canonical = lower(*args) + assert canonical == lower(*args) + lines = canonical.splitlines() + assert lines[d['air_line'] - 1].strip().startswith('borrow.end '), d + assert ' = task.spawn ' in lines[related['air_line'] - 1], related + raw = root / 'lowered.air' + raw.write_text(canonical) + raw_d, = records('check', raw, code=1) + assert (raw_d['line'], raw_d['col']) == (d['air_line'], d['air_col']), raw_d + raw_related, = raw_d['related_locations'] + assert (raw_related['line'], raw_related['col']) == (related['air_line'], related['air_col']) + assert raw_d['task'] == d['task'] and raw_related['value'] == d['task'] + return ds + + +with tempfile.TemporaryDirectory(prefix='aji-cfg-provenance-') as directory: + root = Path(directory) + sources = sorted((CORPUS / 'source/cfg_provenance').glob('*.aji')) + rejected = 0 + for path in sources: + source = path.read_text() + if '// expect: reject' in source: + rejected += 1 + ds = rejection(root, path, path) + twin = re.search(r'^// AIR twin: (.+)$', source, re.MULTILINE) + assert twin, path + expected = records('check', CORPUS / twin[1], code=1) + assert Counter(d['code'] for d in ds) == Counter(d['code'] for d in expected) + else: + assert not records('check', path) + raw = root / 'accepted.air' + raw.write_text(lower(path)) + assert not records('check', raw) + for seed in range(8): + for quantum in (1, 7): + options = ('--fuel', 100000, '--schedule-seed', seed, '--quantum', quantum) + result, = records('run', *options, path) + reference, = records('run', *options, raw) + assert result == reference, (path, result, reference) + assert result['value'] == 7, result + + # Explicitly execute the other tuple permutation; scheduler seeds alone + # cannot change a constant branch condition. + permuted = root / 'permuted.air' + source = (CORPUS / 'phase3/run/cfg_provenance_correlated_scopes.air').read_text() + permuted.write_text(source.replace('const.bool true', 'const.bool false')) + assert not records('check', permuted) + for seed in range(8): + result, = records('run', '--fuel', 100000, '--schedule-seed', seed, '--quantum', 1, permuted) + assert result['value'] == 21, result + + # Package/generic specialization retains the provider's factual positions. + library = root / 'library.aji' + source = (CORPUS / 'source/cfg_provenance/cancel_join_twice_keeps_spawn.aji').read_text() + source = re.sub(r'^module .+$', 'module app.library', source, flags=re.MULTILINE) + library.write_text(source.replace('fn main()', 'fn bad()')) + (root / 'entry.aji').write_text('''module app.entry +import app.library; +fn main() -> u8 effects [task.spawn, task.wait] { + return app.library.bad::(); +} +''') + manifest = root / 'aji.toml' + manifest.write_text('''[package] +name = "provenance" +version = "1" +entry = "entry.aji" +[modules] +app.library = "library.aji" +''') + rejection(root, library, '--manifest', manifest, file='library.aji') + shield = records('check', CORPUS / 'phase3/reject/cfg_provenance_shield_stack_join.air', code=1) + assert [d['code'] for d in shield] == ['E3002', 'E4305'], shield + assert shield[0]['resource'].startswith('%'), shield + +assert rejected == 3, rejected +print(f'source CFG provenance: {checks} CLI checks, {rejected} loan rejection twins')