diff --git a/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc b/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc new file mode 100644 index 00000000..2d3b3e4b --- /dev/null +++ b/formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc @@ -0,0 +1,457 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += Experiment: a provenance fibre as the soundness specification for the v1 borrow cut +:toc: + +Experiment for #553, run against the ADR-028 draft (PR #845, options D, E and +G) and the unsound programs of #847, including the sixteenth (`U-G1`) and the +revised cut D+R4. Module: `BorrowProvenance.agda`. Date: 2026-12-01 (UTC). +Compiler builds probed: `0c9677d` and this branch's head. + +This is an experiment on a toy model. It is not a proof about `lib/borrow.ml`, +and nothing in `lib/` was changed. + +== Result in brief + +The three obligations are stated and proved separately, in the model. + +[cols="1,3,2",options="header"] +|=== +| Obligation | Statement | Needs + +| (i) provenance inclusion +| The set the checker tracks for a reference contains its provenance fibre + at every program point (`G-holds`, `G-everywhere`). +| D (R1–R3) + +| (ii) exclusivity +| After any execution of an accepted program, two usable references to one + place are both shared (`exclusivity`). +| D and R4 + +| (iii) rejection +| A program that gets stuck on a use after move is rejected + (`stuck-rejected`, needs D). A program that reaches a non-exclusive store + is rejected (`aliasing-rejected`, needs D and R4). +| as stated +|=== + +. *Proved (in the model).* All three hold for D+R4. The #554 `pick` example + is rejected. +. *No refutation inside the model.* No D+R4 program escapes; the theorems + exclude one. Five #847 programs were encoded: `U-A2`, `U-B2`, `U-D1`, + `U-E3` and `U-G1`. The first four violate D and falsify (i). `U-G1` + satisfies D and (i), violates R4, and falsifies (ii). So R4 is needed, and + (i) alone does not catch `U-G1`: it is not a provenance failure. +. *Refuted, by measurement: the production checker is not sound on D+R4 as + worded.* Three unsound programs that satisfy R1–R4 are accepted by + `lib/borrow.ml` today (<>). They use only shared references, so + R4 does not touch them. They are not among #847's sixteen. The model's + checker rejects all three. + +So D+R4 has a proof target, and nothing inside the model argues for E. The +measured holes do: by the ADR's own test ("something inside D+R4 still +escapes"), the present implementation fails. Whether to close three more +holes or to take E is the owner's decision. <> says how the options move. + +== The model + +[cols="1,3",options="header"] +|=== +| Part | Content + +| Language +| Owned locals; `&x` and `&mut x`; ref-to-ref copy, annotated with the + static kind of the reference copied (`copy shr r`, `copy mut r`); + `consume(x)`; `*r`; a call to a reference-returning function, with + arguments passed in `ref` mode or as a shared reference by value; a branch + at the bind site; `expire r`. Also the first-class forms behind #847: a + reference in a tuple (`lettup`, `proj`), re-pointing (`assign`, + `assignif`), `&*r` as a primitive (`reborrow`), and a callee that returns + `(&x, 0).0` (`retwrap`). + +| Dynamic semantics +| A store of moved places and reference locals. A reference value *is* the + loan it came from (`loan x k`). `run` returns `nothing` when a step is + stuck: a use of a moved place, a dereference whose owner was moved, or an + unbound name. Branch outcomes come from an oracle `ℕ → Bool`. There is no + write statement. + +| Checker +| Per reference local, a set of loans (`TEnv`). Verdicts read a count per + place and kind (`cnt`, `free`, `noMut`). A copy's kind annotation is + checked against the set. On the first-class forms the checker drops the + "came from" edge, as the lexical checker is observed to: nothing is + tracked for a tuple, for `&*r`, for a wrapped return, or for an assignment + under `if`. It allows `copy mut r`, as the lexical checker does. + +| Cut D+R4 +| `R1`: a type-formation predicate `WF` (a reference is not a component of + an aggregate), applied to every type a statement forms. `R2`: no + assignment to a reference local. `R3`: no `reborrow` primitive; `elab` + rewrites it to a copy. `R4`: no `copy mut r`. `D p` is R1–R3 on every + statement; `R4 p` is separate. +|=== + +`Echo` is echo-types' definition (`proofs/agda/Echo.agda` at `140002f`), +restated at universe level 0 because this directory takes no library. Nothing +else comes from echo-types. Nothing comes from ephapax. + +== Statements + +The fibre is taken over executions. `valueAt p r` maps an execution (an +oracle) to the loan `r` holds after `p`. The fibre over a loan is the set of +executions that leave that loan in `r`. + +[source,agda] +---- +Echo : {A B : Set} (f : A → B) → B → Set +Echo {A} f y = Σ A (λ x → f x ≡ y) + +valueAt : Prog → Var → Oracle → Maybe Loan +valueAt p r ρ = run ρ init p >>= λ s → lookup r (snd s) + +Fibre : Prog → Var → Loan → Set +Fibre p r ℓ = Echo (valueAt p r) (just ℓ) + +G : Prog → Set +G p = {M : List Var} {Γ : TEnv} → chk initC p ≡ just (M , Γ) → + (r : Var) (ℓ : Loan) → Fibre p r ℓ → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (ℓ ∈ L)) + +-- "v is compatible with the references bound before it" +Compat : Loan → Env Loan → Set +Compat (loan x shr) σ = NoMutH x σ -- none of them is exclusive on x +Compat (loan x mut) σ = FreeH x σ -- none of them is on x + +Excl : Env Loan → Set +Excl [] = ⊤ +Excl ((r , v) ∷ σ) = Compat v σ × Excl σ +---- + +Proved, with no postulate and no warning: + +[source,agda] +---- +-- (i) +G-holds : (p : Prog) → D p → G p +G-everywhere : (p q : Prog) → D (p ++ q) → G p + +safety : (p : Prog) → D p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Inv M σ Γ) + +-- (ii) +exclusivity : (p : Prog) → D p → R4 p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Excl σ) + +-- (iii) +stuck-rejected : (p : Prog) → D p → (ρ : Oracle) → + run ρ init p ≡ nothing → chk initC p ≡ nothing +aliasing-rejected : (p : Prog) → D p → R4 p → (ρ : Oracle) {s : Store} → + run ρ init p ≡ just s → ¬ Excl (snd s) → chk initC p ≡ nothing + +K1-rejected : chk initC K1 ≡ nothing -- by running the checker +K1-rejected-by-theorem : chk initC K1 ≡ nothing -- from stuck-rejected +---- + +`K1` is `let r = pick(a); consume(a); *r`. `S10` (a call that may return +either argument, a use, expiry, then a move) and `S12` (a shared reference +copied, both used) are in D+R4 and accepted, so the theorems are not vacuous. + +`Inv` is the invariant that carries (i): the two stores bind the same names, +each held loan is in its tracked set, and no tracked loan is on a moved place. +(ii) is proved on top of it. + +(iii) is the contrapositive of (i)'s safety and of (ii). It says the checker +rejects every *program whose execution goes wrong*. It does not say the +checker rejects only those; the model's checker over-rejects (it has no +inferred liveness). + +== The #847 programs + +`P` is the program point at which the obligation fails. + +[cols="1,3,2,2,3,2",options="header"] +|=== +| Id | Program | In D+R4? | First-class checker | Obligation that fails at `P` | Run + +| `U-A2` (A) +| `let r = &a; let t = (r, 0); consume(a); *(t.0)` +| `UA2-not-D`: fails R1 +| `UA2-accepted` +| (i), `UA2-not-G`: `t` holds `loan a shr`, tracked `[]` +| `UA2-stuck` + +| `U-E3` (E) +| `let r = &x; let r2 = &*r; consume(x); *r2` +| `UE3-not-D`: fails R3 +| `UE3-accepted` +| (i), `UE3-not-G`: `r2` holds `loan x shr`, tracked `[]` +| `UE3-stuck` + +| `U-D1` (D) +| `fn wrap(ref x) -> ref Int { return (&x, 0).0; }` … `let r = wrap(a); consume(a); *r` +| `UD1-not-D`: fails R1 in the callee +| `UD1-accepted` +| (i), `UD1-not-G`: tracked `[]` +| `UD1-stuck` + +| `U-B2` (B) +| `let mut r = pick(a); if c { r = pick(b); } consume(b); *r` +| `UB2-not-D`: fails R2 +| `UB2-accepted` +| (i), `UB2-not-G`: on the taken branch `r` holds `loan b shr`, tracked `[loan a shr]` +| `UB2-stuck` (taken branch) + +| `U-G1` (16th) +| `let r = &mut x; let r2 = r;` (then `*r2 = 99; *r = 100; *r2`) +| in D (`UG1-D`); `UG1-not-R4`: fails R4 +| `UG1-accepted` +| (ii), `UG1-not-Excl`: `r` and `r2` both hold `loan x mut`. (i) *holds*: `UG1-G`. +| `UG1-run` (does not get stuck; the writes are not modelled) +|=== + +For `U-E3`, the elaborated program is in D (`UE3-elab-D`) and is rejected +(`UE3-elab-rejected`). That is R3 followed by the ref-to-ref rule, as the ADR +predicts. The control `K-4` (two direct `&mut x`) is rejected (`K4-rejected`). + +Verdict for each: *D+R4 excludes it.* None satisfies D+R4 and escapes. + +A caveat on how much this shows. In the model the first-class forms are +separate constructors and the cut is defined to exclude them, so "violates +D+R4" is close to true by construction. The informative parts are the +theorems (the cut is enough), the `…-accepted` facts with the failing +obligation (without the cut, the obligation is false), and `UG1-G` (the +provenance statement cannot see `U-G1`). The `expire r` in `U-A2` and `U-E3` +stands for last-use expiry; without it the model's checker rejects them for a +different reason. + +[#measured] +== Measured: three holes inside D+R4 in the production checker + +While choosing what to encode, unsound programs that satisfy the cut were run +through the real compiler (`_build/default/bin/main.exe check`). `pick` and +`consume` are as in the ADR's kit. + +[cols="1,4,2,2",options="header"] +|=== +| Id | Program | Production checker | Model + +| `D-01` +| `fn pass(r: ref Int) -> ref Int { return r; }` … `let r = &a; let s = pass(r); consume(a); *s` +| *accepts* (use after move) +| `D01-rejected`; in D+R4 (`D01-D`, `D01-R4`) + +| `D-06` +| `let r = &a; let s = pick(*r); consume(a); *s` +| *accepts* (use after move) +| `D06-rejected`, reading the argument `*r` as passing `r` + +| `D-19` +| `fn f(ref x: Int, c: Bool) -> ref Int { let r = if c { &x } else { &x }; return r; }` … `let r = f(a, true); consume(a); *r` +| *accepts* (use after move). Also with `match`, and with a block `{ &x }`. +| `D19-rejected`; in D+R4 (`D19-D`, `D19-R4`) +|=== + +A fourth program found the same way, `let r = &mut x; let s = r; *s = 1; +*r = 2; *s`, is `U-G1`, which the #553 thread found independently and added +to #847. R4 excludes it. + +Controls that are rejected, correctly: `pass(&a)` in place of `pass(r)`; +`return if c { &x } else { &x }` and the early-return form in place of the +bound local; `K-1`, `K-2`. Baseline: `U-A2`, `U-B2`, `U-D1`, `U-E3` and +`U-G1` are accepted, as #847 reports. + +Each of the three uses a shared reference only as a parameter type, a +`let`-local or a return type, never re-points one, never writes `&*r`, and +never copies an exclusive reference. So each passes R1–R4 as worded. All +three are obligation (i) failures: the production checker loses a "came +from" edge that the cut does not forbid. + +How they relate to the proof: + +* `D-01` is the `byref` case of `arg-sim`: a reference passed by value must + carry its tracked set through the callee's summary. +* `D-19` is the `retif` case of `F-sim`: the summary must take the union over + the callee's branches. A planted mutation that drops one branch breaks that + proof case (<>). +* `D-06` needs a reading for `*r` in a `ref`-mode argument. R3 covers only + `&*r`. The model treats it as passing `r`. + +Not checked: whether these are recorded elsewhere. A search of +`issues-drafts/`, `docs/SOUNDNESS.adoc`, the "Still deferred" trailer of +`lib/borrow.ml` and the ADR's kit found none of them. No issue was filed from +this session. + +One more observation, not followed up: that trailer says +`let r = if c { &a } else { &b }` is accepted. On `0c9677d` it is rejected +(`consume(b); *r` after it gives a borrow error), as is the `pick` form. + +Reproduction: save each row's program after the kit header from ADR-028 +appendix A.4 and run `main.exe check`. + +== Liveness: a count or a set? + +Only what the proofs used is reported. + +=== For (i) and the use-after-move verdict + +* *The verdict needs a count, and only whether it is zero.* `free` and + `noMut` read `cnt k x Γ`, the number of tracked loans of kind `k` on place + `x`. The proof of (i) reads the counts in one lemma, `Inv-consume`, and + uses one fact: a zero count means no tracked loan is on `x`. +* *Keeping the state needs the sets.* `expire r` removes `r`'s entry. The + counts then fall for exactly the places in `r`'s set. A state made only of + counts cannot take that step. `G` also cannot be stated without the sets. + +=== For (ii), exclusivity + +* *The statement is count-shaped.* `Excl` says: per place, either no usable + exclusive reference, or exactly one usable reference in all. That is a + bound on two counts per place (exclusive ≤ 1; exclusive = 1 implies + shared = 0). No set of loans appears in it. `Excl` is written by recursion + over the store and not as counts; the two forms were not proved equal. +* *The verdicts that establish it read zero or non-zero counts.* `&mut x` + needs both counts on `x` to be zero (`free-held`). `&x` needs the + exclusive count to be zero (`nomut-held`). Those two lemmas are the only + places (ii) reads the checker's state. +* *R4 is not a count.* It is a fact about one reference: its kind. In the + model that is the annotation on `copy`, checked against the reference's + own set (`allKind`). A per-place grade does not carry it; a type does. +* *Maintenance still needs the sets*, for the same reason as above: expiry + must lower the counts of the places one reference held, and a copy of a + shared reference must raise them. + +So a per-place, per-kind occupancy-style grade fits the *verdict* and the +*statement* of (ii), with peak 1 for the exclusive kind. It does not fit the +*bookkeeping*: which entries of the vector change when a reference is made, +copied or dies is given by provenance, which is set-valued. This agrees with +the ADR's paragraph "What survives". Not tested: inferred liveness (expiry +points are given here), loops, two-phase borrows, and whether such a vector +fits occupancy-types' rule that grades are static. + +== Aggregates as a map over fibres + +`lettup-is-letref` is proved by `refl`: dynamically, binding a tuple with one +reference slot is binding that reference. So a checker that gives the +aggregate the set of its component is covered by the `letref` case, and (i) +holds for it with no new proof. + +Argued, not mechanised: for several slots, track the union and let a +projection return the whole union. That is sound and field-insensitive. +Not addressed: field mutation (which is re-pointing, class B, and needs a +union at joins), nested aggregates, closures (class C), and (ii) for +aggregates holding exclusive references. + +For option A this suggests the soundness side of aggregates is cheap for (i). +The constraint-design gap that remains is precision (field sensitivity) and +re-pointing under control flow. The experiment says nothing about either. + +[#adr] +== What changes in ADR-028 + +[cols="1,3",options="header"] +|=== +| Option | Change + +| G +| Verified as *one lemma* of P-3, as the revised ADR treats it: an Agda type + under the canonical flags, provable for D in a model, false for four #847 + programs, and true of `U-G1`. So (i) needs (ii) and (iii) beside it. + +| D+R4 +| *Proved in the model; not yet true of the implementation.* All three + obligations hold for D+R4 against the model's checker, and R4 is shown + necessary (`U-G1`). But `D-01`, `D-06` and `D-19` are inside D+R4 and are + accepted by `lib/borrow.ml`. D+R4's experiment, as the ADR words it, would + fail on them. To pass it D+R4 needs either three checker fixes or three + more rules, for example: no reference-typed by-value parameter (or a + summary for one); a summary through locals bound by `if`, `match` and a + block; `*r` as a `ref`-mode argument is a copy of `r`. + +| E +| Not argued for by the model. Supported by the measurement: each round of + probing the reference surface has found holes the previous rule set did + not cover (15, then `U-G1`, then these three). That is evidence about the + implementation, not a proof that D+R4 cannot be made sound. + +| A +| The aggregate note above; a small narrowing for (i), argued and not proved. +|=== + +Overall: *D+R4 proved against an adequate abstract checker; D+R4 as currently +implemented refuted on three programs.* One result of each kind. + +[#controls] +== What was run + +All under Agda 2.6.3 (Ubuntu 24.04 `agda-bin`). The pinned 2.7.0.1 was not +available, so these are checks and not receipt-grade runs. + +* `just -f formal/justfile check-agda`: 2 modules, exit 0, no warning. +* `just -f formal/justfile check-agda-controls`: all 5 planted controls fail + the gate. +* Nine mutations of `BorrowProvenance.agda`, each in a scratch copy. Each made + Agda fail (exit 42): R3 admits `reborrow`; R1 admits a reference in a + tuple; R2 admits `assignif`; R4 admits `copy mut`; `consume` ignores loans; + `&mut` checks only the exclusive count; a by-value argument is not checked + to be shared; the summary drops a branch; `expire` leaves the dynamic + binding in place. +* The probe programs of <> and `U-G1`, through the real compiler. +* `just check` (lint, `dune runtest`, the five guards): exit 0, 0 test + failures. The container first lacked the `tree-sitter` CLI and the vendored + grammar, which the walker tests require; they were installed + (`cargo install tree-sitter-cli`, `just install-grammar`) and the run + repeated. No test was skipped or changed. + +[cols="2,2",options="header"] +|=== +| Measure | Value + +| `BorrowProvenance.agda`, total lines | 1358 +| of which code (no comments, no blank lines) | 942 +| of which the D+R4 extension (obligations ii and iii, `U-G1`) | about 350 total lines +| Agda check time, both modules | about 4 s +| Agent wall-clock, first read to green gate, obligation (i) | about 20 minutes +| Agent wall-clock, D+R4 extension | about 15 minutes +| First full check of each part | passed with no error and no warning +|=== + +The one tooling cost: under `--cubical-compatible`, a `refl` match that needs +constructor injectivity raises `UnsupportedIndexedMatch`, which the gate +fails. Equations between constructor forms are taken apart with `cong` +(`just-inj`, `state-inv`), and relations are defined by recursion, as the +pilot did. + +== Not established + +* *Any link to `lib/borrow.ml`.* The model's checker was written for this + experiment. The measured holes show the real checker differs from it. +* *Exclusivity under writes.* (ii) is a property of the store of usable + references. There is no write statement, so "a write through one reference + is not seen through another" is not stated. Moving an exclusive reference + (what a user writes instead of the copy R4 forbids) is not modelled either. +* *Completeness.* Nothing says the checker accepts a sound program. +* *Closures (class C), loops, block scopes, a dangling return (`U-A6`, + `K-5`).* Not in the language. +* *Inferred liveness.* Expiry points are part of the program text. +* *Any backend.* #848 (references lowered as copies on core wasm) is outside + the model. +* *Rocq and Lean legs.* None. This is an experiment, so none was attempted, + and the module is `ungraded`. No receipt exists. +* *The pinned Agda.* See above. +* *A different reading of the fibre.* Here the fibre is over executions. If + one reads `f` as the identity on loan-carrying values, the fibre is a + singleton and the statement is the invariant `Inv` itself. + +== Beyond this repository + +* The three holes, if confirmed, belong on the v1 ledger (#563) and in + `docs/SOUNDNESS.adoc`, next to #847. +* If (i) is kept as a lemma of P-3, echo-types could carry a "fibre of a run + map" instance. That is for `hyperpolymath/nextgen-typing` + `docs/TYPE-CONNECTIONS.adoc`, not for this record. +* The liveness note bears on occupancy-types' static-grade rule. It was not + tested there. diff --git a/formal/agda/BorrowProvenance.agda b/formal/agda/BorrowProvenance.agda new file mode 100644 index 00000000..c950abe7 --- /dev/null +++ b/formal/agda/BorrowProvenance.agda @@ -0,0 +1,1358 @@ +{-# OPTIONS --safe --without-K --cubical-compatible #-} +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +-- BorrowProvenance.agda +-- ═════════════════════ +-- EXPERIMENT for #553 / ADR-0028 (PR #845), option G: is an echo-types +-- provenance fibre a provable soundness SPECIFICATION for the v1 cut "D" +-- (second-class references)? The record, with what is and is not +-- established, is `formal/agda/BORROW-PROVENANCE-EXPERIMENT.adoc`. +-- +-- What is modelled (a toy, NOT `lib/borrow.ml`): +-- * owned locals, `&x` / `&mut x`, ref-to-ref copy, `consume`, `*r`, +-- functions returning a reference (`pick`), a branch at the bind site, +-- and an explicit expiry point `expire r`; +-- * the first-class constructs behind #847's classes A, B, D and E, with +-- the checker dropping the "came from" edge as the lexical checker is +-- observed to; +-- * a dynamic semantics in which a reference value IS the loan it came +-- from, and which gets stuck on a use after move; +-- * ADR-0028's rules R1 (type formation), R2 (no re-pointing), R3 (no +-- reborrow primitive) and R4 (an exclusive reference is not copyable) +-- as predicates. +-- +-- What is NOT modelled: writes (exclusivity is proved as a property of the +-- store of usable references, section (e); nothing is said about a write), +-- moving an exclusive reference, closures (class C), loops, block scopes, dangling returns +-- (U-A6 / K-5), inferred liveness (expiry points are given, not computed), +-- and every backend (#848). +-- +-- `Echo` below is echo-types' definition (`proofs/agda/Echo.agda`, commit +-- 140002f) restated at universe level 0, because this directory takes no +-- library: `Echo f y = Σ x. f x ≡ y`, the standard preimage fibre. Nothing +-- else is taken from echo-types, and nothing from ephapax. +-- +-- Checked with exactly `agda --safe --without-K --cubical-compatible` +-- (`just -f formal/justfile check-agda`). Import cone: this file and +-- `Agda.Builtin.{Nat,Bool,Equality,List,Maybe,Sigma}`. +-- +-- A note on style: under these flags a `refl` match that needs constructor +-- injectivity raises UnsupportedIndexedMatch, which the gate fails. So +-- equations between constructor forms are taken apart with `cong`, and +-- `refl` is matched only where one side is a variable. + +module BorrowProvenance where + +open import Agda.Builtin.Nat using (zero; suc; _+_; _==_) renaming (Nat to ℕ) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.Equality using (_≡_; refl) +open import Agda.Builtin.List using (List; []; _∷_) +open import Agda.Builtin.Maybe using (Maybe; just; nothing) +open import Agda.Builtin.Sigma using (Σ; _,_; fst; snd) + +------------------------------------------------------------------------ +-- Logic and small library (defined here; no agda-stdlib) + +data ⊥ : Set where + +record ⊤ : Set where + constructor tt + +infix 3 ¬_ +¬_ : Set → Set +¬ A = A → ⊥ + +infixr 2 _×_ +_×_ : Set → Set → Set +A × B = Σ A (λ _ → B) + +infixr 1 _⊎_ +data _⊎_ (A B : Set) : Set where + inl : A → A ⊎ B + inr : B → A ⊎ B + +sym : {A : Set} {x y : A} → x ≡ y → y ≡ x +sym refl = refl + +trans : {A : Set} {x y z : A} → x ≡ y → y ≡ z → x ≡ z +trans refl e = e + +cong : {A B : Set} (f : A → B) {x y : A} → x ≡ y → f x ≡ f y +cong f refl = refl + +subst : {A : Set} (P : A → Set) {x y : A} → x ≡ y → P x → P y +subst P refl p = p + +infix 0 if_then_else_ +if_then_else_ : {A : Set} → Bool → A → A → A +if true then a else b = a +if false then a else b = b + +not : Bool → Bool +not true = false +not false = true + +infixr 6 _∧_ +_∧_ : Bool → Bool → Bool +true ∧ b = b +false ∧ b = false + +isZero : ℕ → Bool +isZero zero = true +isZero (suc _) = false + +b2n : Bool → ℕ +b2n true = 1 +b2n false = 0 + +infixr 5 _++_ +_++_ : {A : Set} → List A → List A → List A +[] ++ ys = ys +(x ∷ xs) ++ ys = x ∷ (xs ++ ys) + +infixl 1 _>>=_ +_>>=_ : {A B : Set} → Maybe A → (A → Maybe B) → Maybe B +nothing >>= f = nothing +just a >>= f = f a + +when : {A : Set} → Bool → Maybe A → Maybe A +when c m = if c then m else nothing + +fromJust : {A : Set} → A → Maybe A → A +fromJust d nothing = d +fromJust d (just a) = a + +just-inj : {A : Set} {a b : A} → just a ≡ just b → a ≡ b +just-inj {a = a} e = cong (fromJust a) e + +nothing≢just : {A : Set} {a : A} → nothing ≡ just a → ⊥ +nothing≢just () + +false≢true : false ≡ true → ⊥ +false≢true () + +bind-inv : {A B : Set} (m : Maybe A) (f : A → Maybe B) {b : B} → + (m >>= f) ≡ just b → Σ A (λ a → (m ≡ just a) × (f a ≡ just b)) +bind-inv nothing f () +bind-inv (just a) f e = a , refl , e + +bind-intro : {A B : Set} {m : Maybe A} {f : A → Maybe B} {a : A} {b : B} → + m ≡ just a → f a ≡ just b → (m >>= f) ≡ just b +bind-intro refl e = e + +when-inv : {A : Set} (c : Bool) {m : Maybe A} {b : A} → + when c m ≡ just b → (c ≡ true) × (m ≡ just b) +when-inv false () +when-inv true e = refl , e + +when-intro : {A : Set} {c : Bool} {m : Maybe A} → c ≡ true → when c m ≡ m +when-intro refl = refl + +∧-l : (a b : Bool) → (a ∧ b) ≡ true → a ≡ true +∧-l true b e = refl +∧-l false b () + +∧-r : (a b : Bool) → (a ∧ b) ≡ true → b ≡ true +∧-r true b e = e +∧-r false b () + +not-true : (b : Bool) → not b ≡ true → b ≡ false +not-true false e = refl +not-true true () + +zero-+ : (m n : ℕ) → isZero (m + n) ≡ true → + (isZero m ≡ true) × (isZero n ≡ true) +zero-+ zero n e = refl , e +zero-+ (suc m) n () + +b2n-zero : (b : Bool) → isZero (b2n b) ≡ true → b ≡ false +b2n-zero false e = refl +b2n-zero true () + +------------------------------------------------------------------------ +-- The echo fibre (echo-types `Echo`, restated; see the header) + +Echo : {A B : Set} (f : A → B) → B → Set +Echo {A} f y = Σ A (λ x → f x ≡ y) + +------------------------------------------------------------------------ +-- Syntax + +Var : Set +Var = ℕ + +data Kind : Set where + shr mut : Kind + +-- A loan: the place borrowed and the kind of borrow. +data Loan : Set where + loan : Var → Kind → Loan + +owner : Loan → Var +owner (loan x k) = x + +-- Types, only as far as rule R1 needs them. +data Ty : Set where + int ref : Ty + tup : Ty → Ty -- `(T, Int)`: an aggregate with one T slot + +NoRef : Ty → Set +NoRef int = ⊤ +NoRef ref = ⊥ +NoRef (tup t) = NoRef t + +-- R1, type formation: a reference may be a parameter, a let-local or a +-- return type, never a component of an aggregate. +WF : Ty → Set +WF int = ⊤ +WF ref = ⊤ +WF (tup t) = NoRef t + +-- A call argument: an owned local passed in `ref` mode, or a SHARED +-- reference local passed by value (the checker refuses a `&mut` here; the +-- toy has no by-value `&mut` argument). +data Arg : Set where + own : Var → Arg + byref : Var → Arg + +-- The body of a reference-returning function, by parameter index. +data FBody : Set where + ret : ℕ → FBody -- return &p_i (or p_i, a ref) + retif : ℕ → FBody → FBody → FBody -- if c { … } else { … } + retwrap : ℕ → FBody -- return (&p_i, 0).0 (class D) + +data RExp : Set where + borrow : Kind → Var → RExp -- &x, &mut x + copy : Kind → Var → RExp -- r, of type `ref T` (shr) or `mut T` (mut) + reborrow : Kind → Var → RExp -- &*r, &mut *r (class E, first-class) + proj : Var → RExp -- t.0 (class A) + call : FBody → List Arg → RExp -- f(ā) + choose : ℕ → RExp → RExp → RExp -- if c { e₁ } else { e₂ } + +data Stmt : Set where + letref : Var → RExp → Stmt -- let r = e + lettup : Var → RExp → Stmt -- let t = (e, 0) (class A) + assign : Var → RExp → Stmt -- r = e (K-6) + assignif : ℕ → Var → RExp → Stmt -- if c { r = e } (class B) + consume : Var → Stmt -- consume(x): moves x + deref : Var → Stmt -- *r + expire : Var → Stmt -- r is dead from here (given, not inferred) + +Prog : Set +Prog = List Stmt + +------------------------------------------------------------------------ +-- Environments + +Env : Set → Set +Env A = List (Var × A) + +lookup : {A : Set} → Var → Env A → Maybe A +lookup r [] = nothing +lookup r ((s , a) ∷ e) = if r == s then just a else lookup r e + +remove : {A : Set} → Var → Env A → Env A +remove r [] = [] +remove r ((s , a) ∷ e) = if r == s then e else (s , a) ∷ remove r e + +mem : Var → List Var → Bool +mem y [] = false +mem y (x ∷ M) = if x == y then true else mem y M + +nth : {A : Set} → ℕ → List A → Maybe A +nth i [] = nothing +nth zero (a ∷ as) = just a +nth (suc i) (a ∷ as) = nth i as + +------------------------------------------------------------------------ +-- Dynamic semantics (idealised). A reference value is the loan it came +-- from. `nothing` is "stuck": a use after move, or an unbound name. + +Oracle : Set +Oracle = ℕ → Bool -- the run-time value of each branch condition + +Store : Set +Store = List Var × Env Loan -- moved owned locals; reference locals + +alive : List Var → Loan → Bool +alive M ℓ = not (mem (owner ℓ) M) + +evalArg : List Var → Env Loan → Arg → Maybe Loan +evalArg M σ (own x) = when (not (mem x M)) (just (loan x shr)) +evalArg M σ (byref r) = lookup r σ + +evalArgs : List Var → Env Loan → List Arg → Maybe (List Loan) +evalArgs M σ [] = just [] +evalArgs M σ (a ∷ as) = + evalArg M σ a >>= λ v → evalArgs M σ as >>= λ vs → just (v ∷ vs) + +runF : Oracle → FBody → List Loan → Maybe Loan +runF ρ (ret i) vs = nth i vs +runF ρ (retif c b₁ b₂) vs = if ρ c then runF ρ b₁ vs else runF ρ b₂ vs +runF ρ (retwrap i) vs = nth i vs + +evalR : Oracle → List Var → Env Loan → RExp → Maybe Loan +evalR ρ M σ (borrow k x) = when (not (mem x M)) (just (loan x k)) +evalR ρ M σ (copy k r) = lookup r σ +evalR ρ M σ (reborrow k r) = lookup r σ +evalR ρ M σ (proj t) = lookup t σ +evalR ρ M σ (call b as) = evalArgs M σ as >>= runF ρ b +evalR ρ M σ (choose c e₁ e₂) = if ρ c then evalR ρ M σ e₁ else evalR ρ M σ e₂ + +step : Oracle → Store → Stmt → Maybe Store +step ρ (M , σ) (letref r e) = evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ) +step ρ (M , σ) (lettup t e) = evalR ρ M σ e >>= λ v → just (M , (t , v) ∷ σ) +step ρ (M , σ) (assign r e) = + lookup r σ >>= λ _ → evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ) +step ρ (M , σ) (assignif c r e) = + lookup r σ >>= λ _ → + if ρ c then (evalR ρ M σ e >>= λ v → just (M , (r , v) ∷ σ)) else just (M , σ) +step ρ (M , σ) (consume x) = when (not (mem x M)) (just (x ∷ M , σ)) +step ρ (M , σ) (deref r) = lookup r σ >>= λ v → when (alive M v) (just (M , σ)) +step ρ (M , σ) (expire r) = lookup r σ >>= λ _ → just (M , remove r σ) + +run : Oracle → Store → Prog → Maybe Store +run ρ s [] = just s +run ρ s (c ∷ p) = step ρ s c >>= λ s′ → run ρ s′ p + +------------------------------------------------------------------------ +-- The abstract checker. Per reference local it tracks a SET of loans. +-- Its verdicts read only a count per place and kind (`cnt`). + +TEnv : Set +TEnv = Env (List Loan) + +CState : Set +CState = List Var × TEnv + +hit : Kind → Var → Loan → ℕ +hit shr x (loan y shr) = b2n (x == y) +hit shr x (loan y mut) = 0 +hit mut x (loan y shr) = 0 +hit mut x (loan y mut) = b2n (x == y) + +cntL : Kind → Var → List Loan → ℕ +cntL k x [] = 0 +cntL k x (ℓ ∷ L) = hit k x ℓ + cntL k x L + +-- How many tracked loans of kind k are on place x. +cnt : Kind → Var → TEnv → ℕ +cnt k x [] = 0 +cnt k x ((r , L) ∷ Γ) = cntL k x L + cnt k x Γ + +free : Var → TEnv → Bool -- no loan of either kind on x +free x Γ = isZero (cnt shr x Γ) ∧ isZero (cnt mut x Γ) + +noMut : Var → TEnv → Bool -- no `&mut` loan on x +noMut x Γ = isZero (cnt mut x Γ) + +okBorrow : Kind → Var → TEnv → Bool +okBorrow shr x Γ = noMut x Γ +okBorrow mut x Γ = free x Γ + +isKind : Kind → Loan → Bool +isKind shr (loan y shr) = true +isKind shr (loan y mut) = false +isKind mut (loan y shr) = false +isKind mut (loan y mut) = true + +-- Every loan in the set has kind k: the static type of the reference. +allKind : Kind → List Loan → Bool +allKind k [] = true +allKind k (ℓ ∷ L) = isKind k ℓ ∧ allKind k L + +trackArg : List Var → TEnv → Arg → Maybe (List Loan) +trackArg M Γ (own x) = when (not (mem x M) ∧ noMut x Γ) (just (loan x shr ∷ [])) +trackArg M Γ (byref r) = lookup r Γ >>= λ L → when (allKind shr L) (just L) + +trackArgs : List Var → TEnv → List Arg → Maybe (List (List Loan)) +trackArgs M Γ [] = just [] +trackArgs M Γ (a ∷ as) = + trackArg M Γ a >>= λ L → trackArgs M Γ as >>= λ Ls → just (L ∷ Ls) + +-- The return-borrow summary of a function body (the #554 fix), applied to +-- the tracked sets of the arguments. `retwrap` drops the edge (class D). +summF : FBody → List (List Loan) → Maybe (List Loan) +summF (ret i) Ls = nth i Ls +summF (retif c b₁ b₂) Ls = summF b₁ Ls >>= λ L₁ → summF b₂ Ls >>= λ L₂ → just (L₁ ++ L₂) +summF (retwrap i) Ls = nth i Ls >>= λ _ → just [] + +-- `reborrow` records no loan (class E). +trackR : List Var → TEnv → RExp → Maybe (List Loan) +trackR M Γ (borrow k x) = when (not (mem x M) ∧ okBorrow k x Γ) (just (loan x k ∷ [])) +trackR M Γ (copy k r) = lookup r Γ >>= λ L → when (allKind k L) (just L) +trackR M Γ (reborrow k r) = lookup r Γ >>= λ _ → just [] +trackR M Γ (proj t) = lookup t Γ +trackR M Γ (call b as) = trackArgs M Γ as >>= summF b +trackR M Γ (choose c e₁ e₂) = + trackR M Γ e₁ >>= λ L₁ → trackR M Γ e₂ >>= λ L₂ → just (L₁ ++ L₂) + +-- `lettup` tracks nothing for the aggregate (class A); `assignif` leaves +-- the binder's set as it was before the branch (class B). +check : CState → Stmt → Maybe CState +check (M , Γ) (letref r e) = trackR M Γ e >>= λ L → just (M , (r , L) ∷ Γ) +check (M , Γ) (lettup t e) = trackR M Γ e >>= λ _ → just (M , (t , []) ∷ Γ) +check (M , Γ) (assign r e) = + lookup r Γ >>= λ _ → trackR M Γ e >>= λ L → just (M , (r , L) ∷ Γ) +check (M , Γ) (assignif c r e) = + lookup r Γ >>= λ _ → trackR M Γ e >>= λ _ → just (M , Γ) +check (M , Γ) (consume x) = when (not (mem x M) ∧ free x Γ) (just (x ∷ M , Γ)) +check (M , Γ) (deref r) = lookup r Γ >>= λ _ → just (M , Γ) +check (M , Γ) (expire r) = lookup r Γ >>= λ _ → just (M , remove r Γ) + +chk : CState → Prog → Maybe CState +chk s [] = just s +chk s (c ∷ p) = check s c >>= λ s′ → chk s′ p + +init : Store +init = [] , [] + +initC : CState +initC = [] , [] + +------------------------------------------------------------------------ +-- The cut D (ADR-0028 §4.5): R1, R2, R3 as predicates + +R1F : FBody → Set +R1F (ret i) = WF ref +R1F (retif c b₁ b₂) = R1F b₁ × R1F b₂ +R1F (retwrap i) = WF (tup ref) + +R1R : RExp → Set +R1R (borrow k x) = WF ref +R1R (copy k r) = WF ref +R1R (reborrow k r) = WF ref +R1R (proj t) = WF (tup ref) +R1R (call b as) = R1F b +R1R (choose c e₁ e₂) = R1R e₁ × R1R e₂ + +-- R3: `&*r` is not a primitive; it is elaborated to `copy r` (`elabR`). +R3R : RExp → Set +R3R (borrow k x) = ⊤ +R3R (copy k r) = ⊤ +R3R (reborrow k r) = ⊥ +R3R (proj t) = ⊤ +R3R (call b as) = ⊤ +R3R (choose c e₁ e₂) = R3R e₁ × R3R e₂ + +R1S : Stmt → Set +R1S (letref r e) = WF ref × R1R e +R1S (lettup t e) = WF (tup ref) × R1R e +R1S (assign r e) = R1R e +R1S (assignif c r e) = R1R e +R1S (consume x) = ⊤ +R1S (deref r) = ⊤ +R1S (expire r) = ⊤ + +-- R2: a reference local is not assigned to after its `let`. +R2S : Stmt → Set +R2S (letref r e) = ⊤ +R2S (lettup t e) = ⊤ +R2S (assign r e) = ⊥ +R2S (assignif c r e) = ⊥ +R2S (consume x) = ⊤ +R2S (deref r) = ⊤ +R2S (expire r) = ⊤ + +R3S : Stmt → Set +R3S (letref r e) = R3R e +R3S (lettup t e) = R3R e +R3S (assign r e) = R3R e +R3S (assignif c r e) = R3R e +R3S (consume x) = ⊤ +R3S (deref r) = ⊤ +R3S (expire r) = ⊤ + +DS : Stmt → Set +DS s = R1S s × R2S s × R3S s + +D : Prog → Set +D [] = ⊤ +D (s ∷ p) = DS s × D p + +D-prefix : (p q : Prog) → D (p ++ q) → D p +D-prefix [] q d = tt +D-prefix (s ∷ p) q (ds , d) = ds , D-prefix p q d + +-- R3's elaboration. +elabR : RExp → RExp +elabR (borrow k x) = borrow k x +elabR (copy k r) = copy k r +elabR (reborrow k r) = copy k r +elabR (proj t) = proj t +elabR (call b as) = call b as +elabR (choose c e₁ e₂) = choose c (elabR e₁) (elabR e₂) + +elabS : Stmt → Stmt +elabS (letref r e) = letref r (elabR e) +elabS (lettup t e) = lettup t (elabR e) +elabS (assign r e) = assign r (elabR e) +elabS (assignif c r e) = assignif c r (elabR e) +elabS (consume x) = consume x +elabS (deref r) = deref r +elabS (expire r) = expire r + +elab : Prog → Prog +elab [] = [] +elab (s ∷ p) = elabS s ∷ elab p + +------------------------------------------------------------------------ +-- Option G as a type + +-- The loan held by r after running p, as a function of the execution. +valueAt : Prog → Var → Oracle → Maybe Loan +valueAt p r ρ = run ρ init p >>= λ s → lookup r (snd s) + +-- The provenance fibre of r at the point after p, over the loan ℓ: the +-- executions that leave ℓ in r. It is an `Echo` of the run map. +Fibre : Prog → Var → Loan → Set +Fibre p r ℓ = Echo (valueAt p r) (just ℓ) + +infix 4 _∈_ +_∈_ : Loan → List Loan → Set +ℓ ∈ [] = ⊥ +ℓ ∈ (m ∷ L) = (ℓ ≡ m) ⊎ (ℓ ∈ L) + +-- G at the point after p: every loan whose fibre is inhabited is in the +-- set the checker tracks for r there. +G : Prog → Set +G p = {M : List Var} {Γ : TEnv} → chk initC p ≡ just (M , Γ) → + (r : Var) (ℓ : Loan) → Fibre p r ℓ → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (ℓ ∈ L)) + +------------------------------------------------------------------------ +-- The invariant: stores agree, each held loan is tracked, and no tracked +-- loan is on a moved place. + +Live : List Var → List Loan → Set +Live M [] = ⊤ +Live M (ℓ ∷ L) = (mem (owner ℓ) M ≡ false) × Live M L + +Inv : List Var → Env Loan → TEnv → Set +Inv M [] [] = ⊤ +Inv M [] (_ ∷ _) = ⊥ +Inv M (_ ∷ _) [] = ⊥ +Inv M ((r , v) ∷ σ) ((r′ , L) ∷ Γ) = (r ≡ r′) × (v ∈ L) × Live M L × Inv M σ Γ + +-- "m evaluates to a loan that is in L, and L is live." +Good : List Var → Maybe Loan → List Loan → Set +Good M m L = Σ Loan (λ v → (m ≡ just v) × (v ∈ L) × Live M L) + +∈-++l : {v : Loan} (L₁ L₂ : List Loan) → v ∈ L₁ → v ∈ (L₁ ++ L₂) +∈-++l [] L₂ () +∈-++l (m ∷ L₁) L₂ (inl e) = inl e +∈-++l (m ∷ L₁) L₂ (inr i) = inr (∈-++l L₁ L₂ i) + +∈-++r : {v : Loan} (L₁ L₂ : List Loan) → v ∈ L₂ → v ∈ (L₁ ++ L₂) +∈-++r [] L₂ i = i +∈-++r (m ∷ L₁) L₂ i = inr (∈-++r L₁ L₂ i) + +Live-++ : (M : List Var) (L₁ L₂ : List Loan) → Live M L₁ → Live M L₂ → Live M (L₁ ++ L₂) +Live-++ M [] L₂ l₁ l₂ = l₂ +Live-++ M (m ∷ L₁) L₂ (a , l₁) l₂ = a , Live-++ M L₁ L₂ l₁ l₂ + +Live-∈ : (M : List Var) (L : List Loan) {v : Loan} → Live M L → v ∈ L → + mem (owner v) M ≡ false +Live-∈ M [] l () +Live-∈ M (m ∷ L) (a , l) (inl refl) = a +Live-∈ M (m ∷ L) (a , l) (inr i) = Live-∈ M L l i + +Good-bind : {A : Set} {M : List Var} {m : Maybe A} {f : A → Maybe Loan} {a : A} + {L : List Loan} → m ≡ just a → Good M (f a) L → Good M (m >>= f) L +Good-bind refl g = g + +Good-join : (M : List Var) (b : Bool) {m₁ m₂ : Maybe Loan} (L₁ L₂ : List Loan) → + Good M m₁ L₁ → Good M m₂ L₂ → Good M (if b then m₁ else m₂) (L₁ ++ L₂) +Good-join M true L₁ L₂ (v , e , i , l₁) (_ , _ , _ , l₂) = + v , e , ∈-++l L₁ L₂ i , Live-++ M L₁ L₂ l₁ l₂ +Good-join M false L₁ L₂ (_ , _ , _ , l₁) (v , e , i , l₂) = + v , e , ∈-++r L₁ L₂ i , Live-++ M L₁ L₂ l₁ l₂ + +Good-to : {M : List Var} {m : Maybe Loan} {L L′ : List Loan} → + just L ≡ just L′ → Good M m L → Good M m L′ +Good-to {M} {m} e g = subst (Good M m) (just-inj e) g + +-- A fresh borrow of an unmoved place. +borrow-good : (M : List Var) (x : Var) (k : Kind) {L : List Loan} → + not (mem x M) ≡ true → just (loan x k ∷ []) ≡ just L → + Good M (when (not (mem x M)) (just (loan x k))) L +borrow-good M x k nm e = + Good-to e (loan x k , when-intro nm , inl refl , (not-true (mem x M) nm , tt)) + +lookup-rel : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {L : List Loan} → + Inv M σ Γ → lookup r Γ ≡ just L → Good M (lookup r σ) L +lookup-rel M [] [] r inv () +lookup-rel M [] (_ ∷ _) r () +lookup-rel M (_ ∷ _) [] r () +lookup-rel M ((s , v) ∷ σ) ((.s , L′) ∷ Γ) r (refl , i , l , inv) e with r == s +... | true = Good-to e (v , refl , i , l) +... | false = lookup-rel M σ Γ r inv e + +lookup-rel′ : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {v : Loan} → + Inv M σ Γ → lookup r σ ≡ just v → + Σ (List Loan) (λ L → (lookup r Γ ≡ just L) × (v ∈ L)) +lookup-rel′ M [] [] r inv () +lookup-rel′ M [] (_ ∷ _) r () +lookup-rel′ M (_ ∷ _) [] r () +lookup-rel′ M ((s , w) ∷ σ) ((.s , L′) ∷ Γ) r {v} (refl , i , l , inv) e with r == s +... | true = L′ , refl , subst (λ u → u ∈ L′) (just-inj e) i +... | false = lookup-rel′ M σ Γ r inv e + +Inv-remove : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) → + Inv M σ Γ → Inv M (remove r σ) (remove r Γ) +Inv-remove M [] [] r inv = tt +Inv-remove M [] (_ ∷ _) r () +Inv-remove M (_ ∷ _) [] r () +Inv-remove M ((s , v) ∷ σ) ((.s , L) ∷ Γ) r (refl , i , l , inv) with r == s +... | true = inv +... | false = refl , i , l , Inv-remove M σ Γ r inv + +-- Moving x keeps the invariant when no tracked loan is on x. This is the +-- one place the proof reads the counts. +hit-miss : (x : Var) (ℓ : Loan) → isZero (hit shr x ℓ) ≡ true → + isZero (hit mut x ℓ) ≡ true → (x == owner ℓ) ≡ false +hit-miss x (loan y shr) zs zm = b2n-zero (x == y) zs +hit-miss x (loan y mut) zs zm = b2n-zero (x == y) zm + +mem-cons : (x y : Var) (M : List Var) → (x == y) ≡ false → mem y M ≡ false → + mem y (x ∷ M) ≡ false +mem-cons x y M e a with x == y +mem-cons x y M () a | true +mem-cons x y M e a | false = a + +Live-consume : (M : List Var) (x : Var) (L : List Loan) → Live M L → + isZero (cntL shr x L) ≡ true → isZero (cntL mut x L) ≡ true → + Live (x ∷ M) L +Live-consume M x [] l zs zm = tt +Live-consume M x (ℓ ∷ L) (a , l) zs zm = + mem-cons x (owner ℓ) M + (hit-miss x ℓ (fst (zero-+ (hit shr x ℓ) _ zs)) (fst (zero-+ (hit mut x ℓ) _ zm))) a , + Live-consume M x L l (snd (zero-+ (hit shr x ℓ) _ zs)) (snd (zero-+ (hit mut x ℓ) _ zm)) + +Inv-consume : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt shr x Γ) ≡ true → isZero (cnt mut x Γ) ≡ true → + Inv (x ∷ M) σ Γ +Inv-consume M x [] [] inv zs zm = tt +Inv-consume M x [] (_ ∷ _) () +Inv-consume M x (_ ∷ _) [] () +Inv-consume M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zs zm = + e , i , + Live-consume M x L l (fst (zero-+ (cntL shr x L) _ zs)) (fst (zero-+ (cntL mut x L) _ zm)) , + Inv-consume M x σ Γ inv (snd (zero-+ (cntL shr x L) _ zs)) (snd (zero-+ (cntL mut x L) _ zm)) + +------------------------------------------------------------------------ +-- Calls: argument sets and the return summary + +ArgsRel : List Var → List Loan → List (List Loan) → Set +ArgsRel M [] [] = ⊤ +ArgsRel M [] (_ ∷ _) = ⊥ +ArgsRel M (_ ∷ _) [] = ⊥ +ArgsRel M (v ∷ vs) (L ∷ Ls) = (v ∈ L) × Live M L × ArgsRel M vs Ls + +arg-sim : (M : List Var) (σ : Env Loan) (Γ : TEnv) (a : Arg) {L : List Loan} → + Inv M σ Γ → trackArg M Γ a ≡ just L → Good M (evalArg M σ a) L +arg-sim M σ Γ (own x) inv e = + borrow-good M x shr + (∧-l _ _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) e))) + (snd (when-inv (not (mem x M) ∧ noMut x Γ) e)) +arg-sim M σ Γ (byref r) inv e with bind-inv (lookup r Γ) _ e +... | L′ , t , e′ = + Good-to (snd (when-inv (allKind shr L′) e′)) (lookup-rel M σ Γ r inv t) + +args-sim : (M : List Var) (σ : Env Loan) (Γ : TEnv) (as : List Arg) + {Ls : List (List Loan)} → Inv M σ Γ → trackArgs M Γ as ≡ just Ls → + Σ (List Loan) (λ vs → (evalArgs M σ as ≡ just vs) × ArgsRel M vs Ls) +args-sim M σ Γ [] inv e = [] , refl , subst (ArgsRel M []) (just-inj e) tt +args-sim M σ Γ (a ∷ as) inv e + with bind-inv (trackArg M Γ a) _ e +... | L , ta , e₁ with bind-inv (trackArgs M Γ as) _ e₁ +... | Ls′ , tas , e₂ with arg-sim M σ Γ a inv ta | args-sim M σ Γ as inv tas +... | v , ev , i , l | vs , evs , rel = + v ∷ vs , bind-intro ev (bind-intro evs refl) , + subst (ArgsRel M (v ∷ vs)) (just-inj e₂) (i , l , rel) + +nth-rel : (M : List Var) (i : ℕ) (vs : List Loan) (Ls : List (List Loan)) + {L : List Loan} → ArgsRel M vs Ls → nth i Ls ≡ just L → Good M (nth i vs) L +nth-rel M i [] [] rel () +nth-rel M i [] (_ ∷ _) () +nth-rel M i (_ ∷ _) [] () +nth-rel M zero (v ∷ vs) (L′ ∷ Ls) (m , l , rel) e = Good-to e (v , refl , m , l) +nth-rel M (suc i) (v ∷ vs) (L′ ∷ Ls) (m , l , rel) e = nth-rel M i vs Ls rel e + +F-sim : (ρ : Oracle) (M : List Var) (b : FBody) (vs : List Loan) + (Ls : List (List Loan)) {L : List Loan} → R1F b → ArgsRel M vs Ls → + summF b Ls ≡ just L → Good M (runF ρ b vs) L +F-sim ρ M (ret i) vs Ls w rel e = nth-rel M i vs Ls rel e +F-sim ρ M (retwrap i) vs Ls () rel e +F-sim ρ M (retif c b₁ b₂) vs Ls (w₁ , w₂) rel e + with bind-inv (summF b₁ Ls) _ e +... | L₁ , s₁ , e₁ with bind-inv (summF b₂ Ls) _ e₁ +... | L₂ , s₂ , e₂ = + Good-to e₂ (Good-join M (ρ c) L₁ L₂ (F-sim ρ M b₁ vs Ls w₁ rel s₁) + (F-sim ρ M b₂ vs Ls w₂ rel s₂)) + +------------------------------------------------------------------------ +-- Simulation: on the D fragment, what the checker accepts does not get +-- stuck, and the invariant is kept. + +evalR-sim : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (e : RExp) + {L : List Loan} → Inv M σ Γ → R1R e → R3R e → + trackR M Γ e ≡ just L → Good M (evalR ρ M σ e) L +evalR-sim ρ M σ Γ (borrow k x) inv w r3 t = + borrow-good M x k + (∧-l _ _ (fst (when-inv (not (mem x M) ∧ okBorrow k x Γ) t))) + (snd (when-inv (not (mem x M) ∧ okBorrow k x Γ) t)) +evalR-sim ρ M σ Γ (copy k r) inv w r3 t with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = + Good-to (snd (when-inv (allKind k L′) u)) (lookup-rel M σ Γ r inv t′) +evalR-sim ρ M σ Γ (reborrow k r) inv w () t +evalR-sim ρ M σ Γ (proj t′) inv () r3 t +evalR-sim ρ M σ Γ (call b as) inv w r3 t + with bind-inv (trackArgs M Γ as) _ t +... | Ls , ta , sf with args-sim M σ Γ as inv ta +... | vs , ea , rel = Good-bind ea (F-sim ρ M b vs Ls w rel sf) +evalR-sim ρ M σ Γ (choose c e₁ e₂) inv (w₁ , w₂) (p₁ , p₂) t + with bind-inv (trackR M Γ e₁) _ t +... | L₁ , t₁ , u with bind-inv (trackR M Γ e₂) _ u +... | L₂ , t₂ , u′ = + Good-to u′ (Good-join M (ρ c) L₁ L₂ (evalR-sim ρ M σ Γ e₁ inv w₁ p₁ t₁) + (evalR-sim ρ M σ Γ e₂ inv w₂ p₂ t₂)) + +state-inv : {A B : Set} {a a′ : A} {b b′ : B} → + just (a , b) ≡ just (a′ , b′) → (a ≡ a′) × (b ≡ b′) +state-inv e = cong fst (just-inj e) , cong snd (just-inj e) + +Sim : Oracle → List Var → Env Loan → Stmt → List Var → TEnv → Set +Sim ρ M σ s M′ Γ′ = + Σ (Env Loan) (λ σ′ → (step ρ (M , σ) s ≡ just (M′ , σ′)) × Inv M′ σ′ Γ′) + +step-sim : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (s : Stmt) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → DS s → + check (M , Γ) s ≡ just (M′ , Γ′) → Sim ρ M σ s M′ Γ′ +step-sim ρ M σ Γ (lettup t e) inv ((() , _) , _) c +step-sim ρ M σ Γ (assign r e) inv (_ , () , _) c +step-sim ρ M σ Γ (assignif b r e) inv (_ , () , _) c +step-sim ρ M σ Γ (letref r e) inv ((_ , w) , _ , r3) c + with bind-inv (trackR M Γ e) _ c +... | L , t , c′ with evalR-sim ρ M σ Γ e inv w r3 t | state-inv c′ +... | v , ev , i , l | refl , refl = (r , v) ∷ σ , bind-intro ev refl , (refl , i , l , inv) +step-sim ρ M σ Γ (consume x) inv d c + with when-inv (not (mem x M) ∧ free x Γ) c +... | g , c′ with state-inv c′ +... | refl , refl = + σ , when-intro (∧-l _ _ g) , + Inv-consume M x σ Γ inv (∧-l _ _ (∧-r (not (mem x M)) _ g)) + (∧-r _ _ (∧-r (not (mem x M)) _ g)) +step-sim ρ M σ Γ (deref r) inv d c + with bind-inv (lookup r Γ) _ c +... | L , t , c′ with lookup-rel M σ Γ r inv t | state-inv c′ +... | v , ev , i , l | refl , refl = + σ , bind-intro ev (when-intro (cong not (Live-∈ M L l i))) , inv +step-sim ρ M σ Γ (expire r) inv d c + with bind-inv (lookup r Γ) _ c +... | L , t , c′ with lookup-rel M σ Γ r inv t | state-inv c′ +... | v , ev , i , l | refl , refl = + remove r σ , bind-intro ev refl , Inv-remove M σ Γ r inv + +run-sim : (ρ : Oracle) (p : Prog) (M : List Var) (σ : Env Loan) (Γ : TEnv) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → D p → + chk (M , Γ) p ≡ just (M′ , Γ′) → + Σ (Env Loan) (λ σ′ → (run ρ (M , σ) p ≡ just (M′ , σ′)) × Inv M′ σ′ Γ′) +run-sim ρ [] M σ Γ inv d c with state-inv c +... | refl , refl = σ , refl , inv +run-sim ρ (s ∷ p) M σ Γ inv (ds , d) c + with bind-inv (check (M , Γ) s) _ c +... | (M₁ , Γ₁) , cs , c′ with step-sim ρ M σ Γ s inv ds cs +... | σ₁ , es , inv₁ with run-sim ρ p M₁ σ₁ Γ₁ inv₁ d c′ +... | σ′ , er , inv′ = σ′ , bind-intro es er , inv′ + +------------------------------------------------------------------------ +-- (a) The theorems + +-- SAFETY. A D program the checker accepts runs to completion under every +-- execution: no use after move. +safety : (p : Prog) → D p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Inv M σ Γ) +safety p d c ρ = run-sim ρ p [] [] [] tt d c + +-- G. For D programs the tracked set contains the provenance fibre. +G-holds : (p : Prog) → D p → G p +G-holds p d {M} {Γ} c r ℓ (ρ , e) with safety p d c ρ +... | σ , er , inv = + lookup-rel′ M σ Γ r inv + (subst (λ m → (m >>= λ s → lookup r (snd s)) ≡ just ℓ) er e) + +-- G at every program point of a D program (D is prefix-closed). +G-everywhere : (p q : Prog) → D (p ++ q) → G p +G-everywhere p q d = G-holds p (D-prefix p q d) + +-- REJECTION. A D program that gets stuck under some execution is rejected. +maybe-case : {A : Set} (m : Maybe A) → (m ≡ nothing) ⊎ Σ A (λ a → m ≡ just a) +maybe-case nothing = inl refl +maybe-case (just a) = inr (a , refl) + +stuck-rejected : (p : Prog) → D p → (ρ : Oracle) → + run ρ init p ≡ nothing → chk initC p ≡ nothing +stuck-rejected p d ρ stuck with maybe-case (chk initC p) +... | inl e = e +... | inr ((M , Γ) , e) with safety p d e ρ +... | σ , er , inv with nothing≢just (trans (sym stuck) er) +... | () + +------------------------------------------------------------------------ +-- Examples. Owned locals a = 0, b = 1; reference locals r = 10, r₂ = 11, +-- t = 12. `pick` returns `&x` of its `ref` parameter. + +private + a b r r₂ t : Var + a = 0 + b = 1 + r = 10 + r₂ = 11 + t = 12 + + pick : FBody + pick = ret 0 + + yes : Oracle + yes _ = true + + 1≢0 : 1 ≡ 0 → ⊥ + 1≢0 () + + ∈[] : {ℓ : Loan} {L : List Loan} → [] ≡ L → ℓ ∈ L → ⊥ + ∈[] {ℓ} e i = subst (λ L → ℓ ∈ L) (sym e) i + +-- K-1, the #554 `pick` example: let r = pick(a); consume(a); *r +K1 : Prog +K1 = letref r (call pick (own a ∷ [])) ∷ consume a ∷ deref r ∷ [] + +K1-D : D K1 +K1-D = ((tt , tt) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +K1-rejected : chk initC K1 ≡ nothing +K1-rejected = refl + +K1-stuck : (ρ : Oracle) → run ρ init K1 ≡ nothing +K1-stuck ρ = refl + +-- The same verdict, obtained from the theorem instead of by running the checker. +K1-rejected-by-theorem : chk initC K1 ≡ nothing +K1-rejected-by-theorem = stuck-rejected K1 K1-D yes (K1-stuck yes) + +-- K-2: let r = &a; consume(a); *r +K2 : Prog +K2 = letref r (borrow shr a) ∷ consume a ∷ deref r ∷ [] + +K2-rejected : chk initC K2 ≡ nothing +K2-rejected = refl + +-- A D program that IS accepted (so the theorems are not vacuous), S-10 with +-- expiry: let r = first_or(a, b, c); *r; (r dead); consume(a) +S10 : Prog +S10 = letref r (call (retif 0 (ret 0) (ret 1)) (own a ∷ own b ∷ [])) ∷ + deref r ∷ expire r ∷ consume a ∷ [] + +S10-D : D S10 +S10-D = ((tt , (tt , tt)) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +S10-accepted : chk initC S10 ≡ just (a ∷ [] , []) +S10-accepted = refl + +-- At the point after the `let`, r is tracked with both loans; each execution +-- realises one of them. +S10-tracked : chk initC (letref r (call (retif 0 (ret 0) (ret 1)) (own a ∷ own b ∷ [])) ∷ []) + ≡ just ([] , (r , loan a shr ∷ loan b shr ∷ []) ∷ []) +S10-tracked = refl + +------------------------------------------------------------------------ +-- (b) Four #847 programs. For each: it is NOT in D; the first-class +-- checker accepts it; G fails at a point P (a fibre element escapes the +-- tracked set); and it gets stuck (use after move). + +-- U-A2 (class A): let r = &a; let t = (r, 0); consume(a); *(t.0) +UA2-P : Prog -- the point P: after `let t` +UA2-P = letref r (borrow shr a) ∷ lettup t (copy shr r) ∷ expire r ∷ [] + +UA2 : Prog +UA2 = UA2-P ++ (consume a ∷ deref t ∷ []) + +UA2-not-D : ¬ D UA2 -- R1: `(ref Int, Int)` is not well formed +UA2-not-D (_ , ((() , _) , _) , _) + +UA2-accepted : chk initC UA2 ≡ just (a ∷ [] , (t , []) ∷ []) +UA2-accepted = refl + +UA2-stuck : (ρ : Oracle) → run ρ init UA2 ≡ nothing +UA2-stuck ρ = refl + +UA2-not-G : ¬ G UA2-P +UA2-not-G g with g refl t (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- U-E3 (class E): let r = &x; let r₂ = &*r; consume(x); *r₂ +UE3-P : Prog +UE3-P = letref r (borrow shr a) ∷ letref r₂ (reborrow shr r) ∷ expire r ∷ [] + +UE3 : Prog +UE3 = UE3-P ++ (consume a ∷ deref r₂ ∷ []) + +UE3-not-D : ¬ D UE3 -- R3: `&*r` is not a primitive +UE3-not-D (_ , (_ , _ , ()) , _) + +UE3-accepted : chk initC UE3 ≡ just (a ∷ [] , (r₂ , []) ∷ []) +UE3-accepted = refl + +UE3-stuck : (ρ : Oracle) → run ρ init UE3 ≡ nothing +UE3-stuck ρ = refl + +UE3-not-G : ¬ G UE3-P +UE3-not-G g with g refl r₂ (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- Under R3 the reborrow is a copy; the elaborated program is in D and is +-- rejected by the ref-to-ref rule. +UE3-elab-D : D (elab UE3) +UE3-elab-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , (tt , tt , tt) , + (tt , tt , tt) , (tt , tt , tt) , tt + +UE3-elab-rejected : chk initC (elab UE3) ≡ nothing +UE3-elab-rejected = refl + +-- U-D1 (class D): fn wrap(ref x) -> ref Int { return (&x, 0).0; } +-- let r = wrap(a); consume(a); *r +UD1-P : Prog +UD1-P = letref r (call (retwrap 0) (own a ∷ [])) ∷ [] + +UD1 : Prog +UD1 = UD1-P ++ (consume a ∷ deref r ∷ []) + +UD1-not-D : ¬ D UD1 -- R1, inside the callee +UD1-not-D (((_ , ()) , _) , _) + +UD1-accepted : chk initC UD1 ≡ just (a ∷ [] , (r , []) ∷ []) +UD1-accepted = refl + +UD1-stuck : (ρ : Oracle) → run ρ init UD1 ≡ nothing +UD1-stuck ρ = refl + +UD1-not-G : ¬ G UD1-P +UD1-not-G g with g refl r (loan a shr) (yes , refl) +... | L , e , i = ∈[] (just-inj e) i + +-- U-B2 (class B): let mut r = pick(a); if c { r = pick(b); } consume(b); *r +UB2-P : Prog +UB2-P = letref r (call pick (own a ∷ [])) ∷ assignif 0 r (call pick (own b ∷ [])) ∷ [] + +UB2 : Prog +UB2 = UB2-P ++ (consume b ∷ deref r ∷ []) + +UB2-not-D : ¬ D UB2 -- R2: re-pointing +UB2-not-D (_ , (_ , () , _) , _) + +UB2-accepted : chk initC UB2 ≡ just (b ∷ [] , (r , loan a shr ∷ []) ∷ []) +UB2-accepted = refl + +UB2-stuck : run yes init UB2 ≡ nothing -- on the execution that takes the branch +UB2-stuck = refl + +UB2-not-G : ¬ G UB2-P +UB2-not-G g with g refl r (loan b shr) (yes , refl) +... | L , e , i with subst (λ L′ → loan b shr ∈ L′) (sym (just-inj e)) i +... | inl q = 1≢0 (cong owner q) +... | inr () + +------------------------------------------------------------------------ +-- (c) Aggregates. Dynamically `let t = (e, 0)` binds t to the loan of e, +-- exactly as `let r = e` does. So a checker that gives the aggregate the +-- set of its reference component is covered by the `letref` case above. + +lettup-is-letref : (ρ : Oracle) (s : Store) (t′ : Var) (e : RExp) → + step ρ s (lettup t′ e) ≡ step ρ s (letref t′ e) +lettup-is-letref ρ (M , σ) t′ e = refl + +------------------------------------------------------------------------ +-- (d) Three programs that satisfy D as ADR-0028 words it and that the +-- PRODUCTION checker accepts (measured 2026-12-01, build 0c9677d; see the +-- record). The model's checker rejects each, and each is in D, so by +-- `stuck-rejected` it had to. They are holes in `lib/borrow.ml` inside the +-- cut, not counterexamples to G. + +-- D-01: fn pass(r: ref Int) -> ref Int { return r; } +-- let r = &a; let s = pass(r); consume(a); *s +D01 : Prog +D01 = letref r (borrow shr a) ∷ letref r₂ (call (ret 0) (byref r ∷ [])) ∷ + expire r ∷ consume a ∷ deref r₂ ∷ [] + +D01-D : D D01 +D01-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , (tt , tt , tt) , + (tt , tt , tt) , (tt , tt , tt) , tt + +D01-stuck : (ρ : Oracle) → run ρ init D01 ≡ nothing +D01-stuck ρ = refl + +D01-rejected : chk initC D01 ≡ nothing +D01-rejected = stuck-rejected D01 D01-D yes (D01-stuck yes) + +-- D-06: let r = &a; let s = pick(*r); consume(a); *s +-- `*r` in a `ref`-mode argument position is read as passing r (`byref`), the +-- reading R3 gives `&*r`. With that reading it is the same program as D-01. +D06 : Prog +D06 = letref r (borrow shr a) ∷ letref r₂ (call pick (byref r ∷ [])) ∷ + expire r ∷ consume a ∷ deref r₂ ∷ [] + +D06-rejected : chk initC D06 ≡ nothing +D06-rejected = refl + +-- D-19: fn f(ref x: Int, c: Bool) -> ref Int { let r = if c { &x } else { &x }; return r; } +-- let r = f(a, c); consume(a); *r +D19 : Prog +D19 = letref r (call (retif 0 (ret 0) (ret 0)) (own a ∷ [])) ∷ consume a ∷ deref r ∷ [] + +D19-D : D D19 +D19-D = ((tt , (tt , tt)) , tt , tt) , (tt , tt , tt) , (tt , tt , tt) , tt + +D19-stuck : (ρ : Oracle) → run ρ init D19 ≡ nothing +D19-stuck ρ with ρ 0 +... | true = refl +... | false = refl + +D19-rejected : chk initC D19 ≡ nothing +D19-rejected = refl + +------------------------------------------------------------------------ +-- (e) D+R4, and the three obligations stated separately +-- +-- After #847's U-G1 (`let r = &mut x; let r2 = r;` leaves two usable +-- exclusive references) the ADR's surviving cut is D plus +-- R4: an exclusive reference is not copyable. +-- U-G1 is not a provenance failure: G holds for it (`UG1-G`). So the +-- obligations are separate: +-- (i) provenance inclusion — `G-holds` above, needs D only; +-- (ii) exclusivity — `exclusivity` below, needs D and R4; +-- (iii) rejection — `stuck-rejected` above and +-- `aliasing-rejected` below. + +R4R : RExp → Set +R4R (borrow k x) = ⊤ +R4R (copy shr r) = ⊤ +R4R (copy mut r) = ⊥ +R4R (reborrow k r) = ⊤ +R4R (proj t) = ⊤ +R4R (call b as) = ⊤ +R4R (choose c e₁ e₂) = R4R e₁ × R4R e₂ + +R4S : Stmt → Set +R4S (letref r e) = R4R e +R4S (lettup t e) = R4R e +R4S (assign r e) = R4R e +R4S (assignif c r e) = R4R e +R4S (consume x) = ⊤ +R4S (deref r) = ⊤ +R4S (expire r) = ⊤ + +R4 : Prog → Set +R4 [] = ⊤ +R4 (s ∷ p) = R4S s × R4 p + +-- (ii) as a property of the store of usable references. A reference is +-- compatible with the ones bound before it when: if it is exclusive, none of +-- them is on its place; if it is shared, none of them is exclusive on its +-- place. `Excl` asks this of every reference, so any two usable references +-- to one place are both shared. +FreeH : Var → Env Loan → Set +FreeH x [] = ⊤ +FreeH x ((r , v) ∷ σ) = ((x == owner v) ≡ false) × FreeH x σ + +NoMutH : Var → Env Loan → Set +NoMutH x [] = ⊤ +NoMutH x ((r , v) ∷ σ) = (isZero (hit mut x v) ≡ true) × NoMutH x σ + +Compat : Loan → Env Loan → Set +Compat (loan x shr) σ = NoMutH x σ +Compat (loan x mut) σ = FreeH x σ + +Excl : Env Loan → Set +Excl [] = ⊤ +Excl ((r , v) ∷ σ) = Compat v σ × Excl σ + +⊥-elim : {A : Set} → ⊥ → A +⊥-elim () + +==-sym : (m n : ℕ) → (m == n) ≡ (n == m) +==-sym zero zero = refl +==-sym zero (suc n) = refl +==-sym (suc m) zero = refl +==-sym (suc m) (suc n) = ==-sym m n + +∈-miss : (x : Var) (L : List Loan) {v : Loan} → v ∈ L → + isZero (cntL shr x L) ≡ true → isZero (cntL mut x L) ≡ true → + (x == owner v) ≡ false +∈-miss x [] () +∈-miss x (m ∷ L) (inl refl) zs zm = + hit-miss x m (fst (zero-+ (hit shr x m) _ zs)) (fst (zero-+ (hit mut x m) _ zm)) +∈-miss x (m ∷ L) (inr i) zs zm = + ∈-miss x L i (snd (zero-+ (hit shr x m) _ zs)) (snd (zero-+ (hit mut x m) _ zm)) + +∈-nomut : (x : Var) (L : List Loan) {v : Loan} → v ∈ L → + isZero (cntL mut x L) ≡ true → isZero (hit mut x v) ≡ true +∈-nomut x [] () +∈-nomut x (m ∷ L) (inl refl) zm = fst (zero-+ (hit mut x m) _ zm) +∈-nomut x (m ∷ L) (inr i) zm = ∈-nomut x L i (snd (zero-+ (hit mut x m) _ zm)) + +-- Zero counts in the checker's state mean no usable reference is there. +free-held : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt shr x Γ) ≡ true → isZero (cnt mut x Γ) ≡ true → FreeH x σ +free-held M x [] [] inv zs zm = tt +free-held M x [] (_ ∷ _) () +free-held M x (_ ∷ _) [] () +free-held M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zs zm = + ∈-miss x L i (fst (zero-+ (cntL shr x L) _ zs)) (fst (zero-+ (cntL mut x L) _ zm)) , + free-held M x σ Γ inv (snd (zero-+ (cntL shr x L) _ zs)) (snd (zero-+ (cntL mut x L) _ zm)) + +nomut-held : (M : List Var) (x : Var) (σ : Env Loan) (Γ : TEnv) → Inv M σ Γ → + isZero (cnt mut x Γ) ≡ true → NoMutH x σ +nomut-held M x [] [] inv zm = tt +nomut-held M x [] (_ ∷ _) () +nomut-held M x (_ ∷ _) [] () +nomut-held M x ((r , v) ∷ σ) ((r′ , L) ∷ Γ) (e , i , l , inv) zm = + ∈-nomut x L i (fst (zero-+ (cntL mut x L) _ zm)) , + nomut-held M x σ Γ inv (snd (zero-+ (cntL mut x L) _ zm)) + +shr-only : (L : List Loan) {y : Var} → allKind shr L ≡ true → loan y mut ∈ L → ⊥ +shr-only [] a () +shr-only (m ∷ L) a (inr i) = shr-only L (∧-r (isKind shr m) _ a) i +shr-only (m ∷ L) a (inl refl) = false≢true a + +FreeH-lookup : (z : Var) (σ : Env Loan) (r : Var) {u : Loan} → FreeH z σ → + lookup r σ ≡ just u → (z == owner u) ≡ false +FreeH-lookup z [] r f () +FreeH-lookup z ((s , w) ∷ σ) r {u} (f , fs) e with r == s +... | true = subst (λ u′ → (z == owner u′) ≡ false) (just-inj e) f +... | false = FreeH-lookup z σ r fs e + +-- A usable shared reference to y means no usable exclusive one to y. +held-here : (y : Var) (σ : Env Loan) (w : Loan) → w ≡ loan y shr → Compat w σ → + (isZero (hit mut y w) ≡ true) × NoMutH y σ +held-here y σ w refl c = refl , c + +newer-ok : (y : Var) (σ : Env Loan) (r : Var) (w : Loan) → Compat w σ → + lookup r σ ≡ just (loan y shr) → isZero (hit mut y w) ≡ true +newer-ok y σ r (loan z shr) c e = refl +newer-ok y σ r (loan z mut) c e = + cong (λ b → isZero (b2n b)) (trans (==-sym y z) (FreeH-lookup z σ r c e)) + +held-shr-nomut : (σ : Env Loan) (r : Var) (y : Var) → Excl σ → + lookup r σ ≡ just (loan y shr) → NoMutH y σ +held-shr-nomut [] r y ex () +held-shr-nomut ((s , w) ∷ σ) r y (c , ex) e with r == s +... | true = held-here y σ w (just-inj e) c +... | false = newer-ok y σ r w c e , held-shr-nomut σ r y ex e + +-- R4 at work: a copy of a reference whose set is all-shared is compatible. +ref-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (r : Var) {L : List Loan} + (v : Loan) → Inv M σ Γ → Excl σ → lookup r Γ ≡ just L → + allKind shr L ≡ true → lookup r σ ≡ just v → Compat v σ +ref-compat M σ Γ r (loan y shr) inv ex t a e = held-shr-nomut σ r y ex e +ref-compat M σ Γ r {L} (loan y mut) inv ex t a e with lookup-rel′ M σ Γ r inv e +... | L′ , t′ , i = + ⊥-elim (shr-only L a (subst (λ K → loan y mut ∈ K) (just-inj (trans (sym t′) t)) i)) + +AllC : Env Loan → List Loan → Set +AllC σ [] = ⊤ +AllC σ (v ∷ vs) = Compat v σ × AllC σ vs + +arg-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (a′ : Arg) {L : List Loan} + {v : Loan} → Inv M σ Γ → Excl σ → trackArg M Γ a′ ≡ just L → + evalArg M σ a′ ≡ just v → Compat v σ +arg-compat M σ Γ (own x) {v = v} inv ex t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (nomut-held M x σ Γ inv + (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) t)))) +arg-compat M σ Γ (byref r) {v = v} inv ex t e with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = ref-compat M σ Γ r v inv ex t′ (fst (when-inv (allKind shr L′) u)) e + +args-compat : (M : List Var) (σ : Env Loan) (Γ : TEnv) (as : List Arg) + {Ls : List (List Loan)} {vs : List Loan} → Inv M σ Γ → Excl σ → + trackArgs M Γ as ≡ just Ls → evalArgs M σ as ≡ just vs → AllC σ vs +args-compat M σ Γ [] inv ex t e = subst (AllC σ) (just-inj e) tt +args-compat M σ Γ (a′ ∷ as) inv ex t e + with bind-inv (trackArg M Γ a′) _ t | bind-inv (evalArg M σ a′) _ e +... | L , ta , t₁ | v , ea , e₁ + with bind-inv (trackArgs M Γ as) _ t₁ | bind-inv (evalArgs M σ as) _ e₁ +... | Ls′ , tas , t₂ | vs′ , eas , e₂ = + subst (AllC σ) (just-inj e₂) + (arg-compat M σ Γ a′ inv ex ta ea , args-compat M σ Γ as inv ex tas eas) + +nth-compat : (σ : Env Loan) (i : ℕ) (vs : List Loan) {v : Loan} → AllC σ vs → + nth i vs ≡ just v → Compat v σ +nth-compat σ i [] ac () +nth-compat σ zero (u ∷ vs) (c , ac) e = subst (λ w → Compat w σ) (just-inj e) c +nth-compat σ (suc i) (u ∷ vs) (c , ac) e = nth-compat σ i vs ac e + +F-compat : (ρ : Oracle) (σ : Env Loan) (b′ : FBody) (vs : List Loan) {v : Loan} → + R1F b′ → AllC σ vs → runF ρ b′ vs ≡ just v → Compat v σ +F-compat ρ σ (ret i) vs w ac e = nth-compat σ i vs ac e +F-compat ρ σ (retwrap i) vs () ac e +F-compat ρ σ (retif c b₁ b₂) vs (w₁ , w₂) ac e with ρ c +... | true = F-compat ρ σ b₁ vs w₁ ac e +... | false = F-compat ρ σ b₂ vs w₂ ac e + +evalR-compat : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (e : RExp) + {L : List Loan} {v : Loan} → Inv M σ Γ → Excl σ → + R1R e → R3R e → R4R e → trackR M Γ e ≡ just L → + evalR ρ M σ e ≡ just v → Compat v σ +evalR-compat ρ M σ Γ (borrow shr x) inv ex w r3 r4 t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (nomut-held M x σ Γ inv + (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ noMut x Γ) t)))) +evalR-compat ρ M σ Γ (borrow mut x) inv ex w r3 r4 t e = + subst (λ u → Compat u σ) (just-inj (snd (when-inv (not (mem x M)) e))) + (free-held M x σ Γ inv + (∧-l _ _ (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ free x Γ) t)))) + (∧-r _ _ (∧-r (not (mem x M)) _ (fst (when-inv (not (mem x M) ∧ free x Γ) t))))) +evalR-compat ρ M σ Γ (copy shr r) {v = v} inv ex w r3 r4 t e + with bind-inv (lookup r Γ) _ t +... | L′ , t′ , u = ref-compat M σ Γ r v inv ex t′ (fst (when-inv (allKind shr L′) u)) e +evalR-compat ρ M σ Γ (copy mut r) inv ex w r3 () t e +evalR-compat ρ M σ Γ (reborrow k r) inv ex w () r4 t e +evalR-compat ρ M σ Γ (proj t′) inv ex () r3 r4 t e +evalR-compat ρ M σ Γ (call b′ as) inv ex w r3 r4 t e + with bind-inv (trackArgs M Γ as) _ t | bind-inv (evalArgs M σ as) _ e +... | Ls , ta , _ | vs , ea , rf = + F-compat ρ σ b′ vs w (args-compat M σ Γ as inv ex ta ea) rf +evalR-compat ρ M σ Γ (choose c e₁ e₂) inv ex (w₁ , w₂) (p₁ , p₂) (q₁ , q₂) t e + with bind-inv (trackR M Γ e₁) _ t +... | L₁ , t₁ , u with bind-inv (trackR M Γ e₂) _ u +... | L₂ , t₂ , _ with ρ c +... | true = evalR-compat ρ M σ Γ e₁ inv ex w₁ p₁ q₁ t₁ e +... | false = evalR-compat ρ M σ Γ e₂ inv ex w₂ p₂ q₂ t₂ e + +Compat-remove : (v : Loan) (σ : Env Loan) (r : Var) → Compat v σ → Compat v (remove r σ) +FreeH-remove : (x : Var) (σ : Env Loan) (r : Var) → FreeH x σ → FreeH x (remove r σ) +NoMutH-remove : (x : Var) (σ : Env Loan) (r : Var) → NoMutH x σ → NoMutH x (remove r σ) + +FreeH-remove x [] r f = tt +FreeH-remove x ((s , w) ∷ σ) r (f , fs) with r == s +... | true = fs +... | false = f , FreeH-remove x σ r fs + +NoMutH-remove x [] r f = tt +NoMutH-remove x ((s , w) ∷ σ) r (f , fs) with r == s +... | true = fs +... | false = f , NoMutH-remove x σ r fs + +Compat-remove (loan x shr) σ r c = NoMutH-remove x σ r c +Compat-remove (loan x mut) σ r c = FreeH-remove x σ r c + +Excl-remove : (σ : Env Loan) (r : Var) → Excl σ → Excl (remove r σ) +Excl-remove [] r ex = tt +Excl-remove ((s , w) ∷ σ) r (c , ex) with r == s +... | true = ex +... | false = Compat-remove w σ r c , Excl-remove σ r ex + +step-excl : (ρ : Oracle) (M : List Var) (σ : Env Loan) (Γ : TEnv) (s : Stmt) + {M′ M″ : List Var} {Γ′ : TEnv} {σ′ : Env Loan} → + Inv M σ Γ → Excl σ → DS s → R4S s → + check (M , Γ) s ≡ just (M′ , Γ′) → + step ρ (M , σ) s ≡ just (M″ , σ′) → Excl σ′ +step-excl ρ M σ Γ (lettup t e) inv ex ((() , _) , _) r4 c st +step-excl ρ M σ Γ (assign r e) inv ex (_ , () , _) r4 c st +step-excl ρ M σ Γ (assignif b′ r e) inv ex (_ , () , _) r4 c st +step-excl ρ M σ Γ (letref r e) inv ex ((_ , w) , _ , r3) r4 c st + with bind-inv (trackR M Γ e) _ c | bind-inv (evalR ρ M σ e) _ st +... | L , t , _ | v , ev , st′ with state-inv st′ +... | _ , refl = evalR-compat ρ M σ Γ e inv ex w r3 r4 t ev , ex +step-excl ρ M σ Γ (consume x) inv ex d r4 c st + with state-inv (snd (when-inv (not (mem x M)) st)) +... | _ , refl = ex +step-excl ρ M σ Γ (deref r) inv ex d r4 c st + with bind-inv (lookup r σ) _ st +... | v , ev , st′ with state-inv (snd (when-inv (alive M v) st′)) +... | _ , refl = ex +step-excl ρ M σ Γ (expire r) inv ex d r4 c st + with bind-inv (lookup r σ) _ st +... | v , ev , st′ with state-inv st′ +... | _ , refl = Excl-remove σ r ex + +run-excl : (ρ : Oracle) (p : Prog) (M : List Var) (σ : Env Loan) (Γ : TEnv) + {M′ : List Var} {Γ′ : TEnv} → Inv M σ Γ → Excl σ → D p → R4 p → + chk (M , Γ) p ≡ just (M′ , Γ′) → + Σ (Env Loan) (λ σ′ → (run ρ (M , σ) p ≡ just (M′ , σ′)) × Excl σ′) +run-excl ρ [] M σ Γ inv ex d r4 c with state-inv c +... | refl , refl = σ , refl , ex +run-excl ρ (s ∷ p) M σ Γ inv ex (ds , d) (r4s , r4) c + with bind-inv (check (M , Γ) s) _ c +... | (M₁ , Γ₁) , cs , c′ with step-sim ρ M σ Γ s inv ds cs +... | σ₁ , es , inv₁ + with run-excl ρ p M₁ σ₁ Γ₁ inv₁ (step-excl ρ M σ Γ s inv ex ds r4s cs es) d r4 c′ +... | σ′ , er , ex′ = σ′ , bind-intro es er , ex′ + +-- (ii) EXCLUSIVITY. After any execution of an accepted D+R4 program, two +-- usable references to one place are both shared. +exclusivity : (p : Prog) → D p → R4 p → {M : List Var} {Γ : TEnv} → + chk initC p ≡ just (M , Γ) → (ρ : Oracle) → + Σ (Env Loan) (λ σ → (run ρ init p ≡ just (M , σ)) × Excl σ) +exclusivity p d r4 c ρ = run-excl ρ p [] [] [] tt tt d r4 c + +-- (iii) REJECTION, the half for (ii): a D+R4 program some execution of which +-- reaches a store that is not exclusive is rejected. (`stuck-rejected` is +-- the half for use after move.) +aliasing-rejected : (p : Prog) → D p → R4 p → (ρ : Oracle) {s : Store} → + run ρ init p ≡ just s → ¬ Excl (snd s) → chk initC p ≡ nothing +aliasing-rejected p d r4 ρ {s} h nx with maybe-case (chk initC p) +... | inl e = e +... | inr ((M , Γ) , e) with exclusivity p d r4 e ρ +... | σ , er , ex = + ⊥-elim (nx (subst (λ s′ → Excl (snd s′)) (sym (just-inj (trans (sym h) er))) ex)) + +-- U-G1 (#847, the 16th): let r = &mut x; let r2 = r; (then *r2 = …; *r = …) +UG1 : Prog +UG1 = letref r (borrow mut a) ∷ letref r₂ (copy mut r) ∷ [] + +UG1-D : D UG1 -- it passes R1, R2 and R3 +UG1-D = ((tt , tt) , tt , tt) , ((tt , tt) , tt , tt) , tt + +UG1-not-R4 : ¬ R4 UG1 -- R4: an exclusive reference is copied +UG1-not-R4 (_ , () , _) + +UG1-accepted : chk initC UG1 + ≡ just ([] , (r₂ , loan a mut ∷ []) ∷ (r , loan a mut ∷ []) ∷ []) +UG1-accepted = refl + +UG1-run : (ρ : Oracle) → run ρ init UG1 + ≡ just ([] , (r₂ , loan a mut) ∷ (r , loan a mut) ∷ []) +UG1-run ρ = refl + +UG1-not-Excl : ¬ Excl ((r₂ , loan a mut) ∷ (r , loan a mut) ∷ []) +UG1-not-Excl ((() , _) , _) + +-- It is NOT a provenance failure: G holds, because U-G1 is in D. +UG1-G : G UG1 +UG1-G = G-holds UG1 UG1-D + +-- K-4, the control: let r = &mut x; let r2 = &mut x; +K4 : Prog +K4 = letref r (borrow mut a) ∷ letref r₂ (borrow mut a) ∷ [] + +K4-rejected : chk initC K4 ≡ nothing +K4-rejected = refl + +-- A D+R4 program that is accepted, so (ii) is not vacuous: +-- let r = &a; let r2 = r; (both usable) +S12 : Prog +S12 = letref r (borrow shr a) ∷ letref r₂ (copy shr r) ∷ deref r ∷ deref r₂ ∷ [] + +S12-accepted : chk initC S12 + ≡ just ([] , (r₂ , loan a shr ∷ []) ∷ (r , loan a shr ∷ []) ∷ []) +S12-accepted = refl + +-- D-01, D-06 and D-19 above use only shared references, so they are in D+R4 +-- too. R4 does not touch the three production holes they record. +D01-R4 : R4 D01 +D01-R4 = tt , tt , tt , tt , tt , tt + +D19-R4 : R4 D19 +D19-R4 = tt , tt , tt , tt diff --git a/formal/agda/README.adoc b/formal/agda/README.adoc index a1b5e8a3..1cc991ce 100644 --- a/formal/agda/README.adoc +++ b/formal/agda/README.adoc @@ -24,6 +24,14 @@ file, checked from this directory. `formal/QttSemiring.v` (obligation P-4) | Checks clean under the canonical flags on Agda 2.6.3. *Not yet checked on the pinned Agda 2.7.0.1.* No Lean leg. No receipt. So still `ungraded`. + +| `BorrowProvenance.agda` +| *Experiment* (#553, ADR-028 option G): on a toy reference calculus, the + checker's tracked loan set contains the provenance fibre for every program + in the second-class cut D; exclusivity and rejection for D+R4 +| Checks clean under the canonical flags on Agda 2.6.3. A toy model, not + `lib/borrow.ml`. No Rocq or Lean leg, no receipt: `ungraded`. Record: + `BORROW-PROVENANCE-EXPERIMENT.adoc`. |=== == Checking