blob: 7e66bc477ca120df95f03f7a5e92e7ed84380343 [file]
-- Copyright 2026 The Fuchsia Authors
--
-- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
-- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
-- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
-- This file may not be copied, modified, or distributed except according to
-- those terms.
module
prelude
public import Init.Core
public import Init.NotationExtra
public import Init.Data.Nat.Basic
public import Init.Data.List.Basic
public import Init.Data.Option.Basic
public import Trusted.Framework
public import Anneal.InitLemmas
public import Anneal.Framework.StepWp
public import Anneal.Hybrid
public import Anneal.Backend
public section
/-!
# Zero-TCB Non-Vacuous Gate and Dialect RulePack Builders
(`Anneal.Hybrid.ExtGateKit`)
Pass-1 (`0`-TCB, `0` `._unsafe_rec`) builders over `Anneal.Hybrid` and
`Anneal.Backend` for non-vacuous witness gates, open dialect operations, and
composable dialect rewrite passes without modifying `anneal/trusted/`:
1. **Witness-Free and Non-Vacuous Subgoal Gates (`mkWitnessFreeGate`,
`NonVacuousGate`, `mkNonVacuousSubgoalGate`, `nonVacuousGate_inhabited`):**
Specializes `Anneal.Hybrid.CertifiedGate` for self-checking outputs and pairs
witness-bounded checkers with a constructive accepted-input witness so
checkers that reject every input are statically ruled out.
2. **Open `(dialectId, opId, imm)` Dialect Operations (`ExtDialectOp`,
`DialectSemTable`, `normalizePoisonWord64`, `evalExtDialectOp`):** Extends
`Anneal.Backend.SsaOp` outside `Anneal.Backend.Rules` (`0` `_sparseCasesOn`
growth) with open natural-number dialect tags and 64-bit `WellTypedVal`
normalization.
3. **Composable Non-Vacuous Dialect `RulePack` Gates (`DialectRuleSpec`,
`DialectRulePack`, `mkDialectRulePackGate`,
`dialectRulePack_entry_inhabited`):** Packages domain rewrite rules into a
`CertifiedGate` whose specification `(UnitValid tgt ∧ SemRefinesUnder ...)`
composes directly with `Anneal.Backend.composePassGates` and
`liftContractAlongRefinement` while guaranteeing `∃ q, EntryPre src q`.
-/
namespace Anneal.Hybrid.ExtGateKit
open Trusted.Framework Anneal.InitLemmas Anneal.Framework.StepWp
open Anneal.Hybrid Anneal.Backend
/-! ## 1. Witness-Free and Non-Vacuous `CertifiedGate` Builders -/
/-- Witness-free specialization (`W := Unit`, `maxWitness := 0`, `wSize := 0`)
for self-checking candidate outputs (such as layout metadata or section
alignments). -/
@[expose] def mkWitnessFreeGate {X Y : Type}
(Pre : X → Prop) (Spec : X → Y → Prop)
(check : X → Y → Bool)
(hSound : ∀ x y, Pre x → check x y = true → Spec x y) :
CertifiedGate X Y Unit Pre Spec where
maxWitness := fun _ => 0
wSize := fun _ => 0
check := fun x y _ => check x y
sound := fun x y _ hPre _ hChk => hSound x y hPre hChk
/-- Anti-vacuity wrapper pairing a `CertifiedGate` with a constructive witness
that at least one valid input `x0` has an accepted `(y0, w0)` candidate. -/
structure NonVacuousGate (X Y W : Type) (Pre : X → Prop)
(Spec : X → Y → Prop) where
gate : CertifiedGate X Y W Pre Spec
nonEmpty : ∃ (x0 : X) (y0 : Y) (w0 : W),
Pre x0 ∧ gateCheckBounded gate (x0, y0, w0) = true
/-- Build a `NonVacuousGate` from a bounded witness checker together with one
concrete accepted triple `(x0, y0, w0)`. -/
@[expose] def mkNonVacuousSubgoalGate {X Y W : Type}
(Pre : X → Prop) (Spec : X → Y → Prop)
(maxWitness : X → Nat) (wSize : W → Nat)
(check : X → Y → W → Bool)
(hSound : ∀ x y w, Pre x → wSize w ≤ maxWitness x →
check x y w = true → Spec x y)
(x0 : X) (y0 : Y) (w0 : W)
(hPre0 : Pre x0)
(hAccept0 : (Nat.ble (wSize w0) (maxWitness x0) && check x0 y0 w0) = true) :
NonVacuousGate X Y W Pre Spec where
gate :=
{ maxWitness := maxWitness
wSize := wSize
check := check
sound := hSound }
nonEmpty := ⟨x0, y0, w0, hPre0, hAccept0⟩
/-- Every `NonVacuousGate` admits at least one `.ok` run of `evalGate` whose
output satisfies `Spec`. -/
theorem nonVacuousGate_inhabited {X Y W E : Type}
{Pre : X → Prop} {Spec : X → Y → Prop}
(nv : NonVacuousGate X Y W Pre Spec) :
∃ (x0 : X) (y0 : Y) (w0 : W),
Pre x0 ∧
evalGate (E := E) nv.gate x0 (.candidate y0 w0) = .ok y0 ∧
Spec x0 y0 := by
have ⟨x0, y0, w0, hPre, hBnd⟩ := nv.nonEmpty
have hOk : evalGate (E := E) nv.gate x0 (.candidate y0 w0) = .ok y0 :=
(gateCheckBounded_iff_evalGate nv.gate x0 y0 w0).1 hBnd
exact ⟨x0, y0, w0, hPre, hOk,
evalGate_sound nv.gate x0 (.candidate y0 w0) y0 hPre hOk⟩
/-! ## 2. Open `(dialectId, opId, imm)` Dialect Ops Over `PoisonOr Nat` -/
/-- Open SSA operator sum extending `Anneal.Backend.SsaOp` with domain-specific
`(dialectId, opId, imm)` operations without modifying `Anneal.Backend.Rules`. -/
inductive ExtDialectOp where
| core (op : SsaOp)
| ext (dialectId opId imm : Nat)
@[expose] def ExtDialectOp.beq : ExtDialectOp → ExtDialectOp → Bool
| .core a, .core b => SsaOp.beq a b
| .ext d1 o1 i1, .ext d2 o2 i2 =>
Nat.beq d1 d2 && Nat.beq o1 o2 && Nat.beq i1 i2
| .core _, .ext _ _ _ => false
| .ext _ _ _, .core _ => false
theorem extDialectOp_eq_of_beq :
∀ {a b : ExtDialectOp}, ExtDialectOp.beq a b = true → a = b
| .core x, .core y, h => congrArg ExtDialectOp.core (ssaOp_eq_of_beq h)
| .ext d1 o1 i1, .ext d2 o2 i2, h => by
have hI := nat_eq_of_beq (bool_and_right h)
have hDO := bool_and_left h
have hO := nat_eq_of_beq (bool_and_right hDO)
have hD := nat_eq_of_beq (bool_and_left hDO)
rw [hD, hO, hI]
| .core _, .ext _ _ _, h => nomatch h
| .ext _ _ _, .core _, h => nomatch h
/-- Normalize any `PoisonOr Nat` payload modulo `2 ^ 64` so dialect semantics
automatically preserve `WellTypedVal`. -/
@[expose] def normalizePoisonWord64 : PoisonOr Nat → PoisonOr Nat
| .poison => .poison
| .val v => .val (word64 v)
theorem normalizePoisonWord64_wellTyped (p : PoisonOr Nat) :
WellTypedVal (normalizePoisonWord64 p) := by
cases p with
| poison => exact True.intro
| val v => exact word64_lt v
/-- Dialect semantics table mapping `(dialectId, opId, imm)` to a `PoisonOr Nat`
evaluator. Unregistered `(dialectId, opId)` pairs return `.poison` (failing
closed under `refinesPoison`). -/
structure DialectSemTable where
evalExt : (Nat → Nat) → Nat → Nat → Nat → List (PoisonOr Nat) → PoisonOr Nat
/-- Evaluate an `ExtDialectOp`, delegating `.core` to `Anneal.Backend.evalSsaOp`
and `.ext` to `tbl.evalExt` normalized to 64 bits. -/
@[expose] def evalExtDialectOp (tbl : DialectSemTable) (env : Nat → Nat)
(op : ExtDialectOp) (args : List (PoisonOr Nat)) : PoisonOr Nat :=
match op with
| .core sop => evalSsaOp env sop args
| .ext dialectId opId imm =>
normalizePoisonWord64 (tbl.evalExt env dialectId opId imm args)
theorem evalExtDialectOp_wellTyped (tbl : DialectSemTable) (env : Nat → Nat)
(op : ExtDialectOp) (args : List (PoisonOr Nat)) :
WellTypedVal (evalExtDialectOp tbl env op args) := by
cases op with
| core sop => exact evalSsaOp_wellTyped env sop args
| ext _ _ _ => exact normalizePoisonWord64_wellTyped _
/-! ## 3. Composable Non-Vacuous Dialect `RulePack` Gates -/
/-- One checked rewrite rule inside a `DialectRulePack` over representation
`BlockRep` with semantics `evalBlock`. -/
structure DialectRuleSpec (Q Val Mem BlockRep : Type)
(EntryPre : BlockRep → Q → Prop)
(evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop) where
ruleId : Nat
checkApply : BlockRep → BlockRep → Bool
sound : ∀ src tgt, checkApply src tgt = true →
SemRefinesUnder (EntryPre src) (evalBlock src) (evalBlock tgt)
/-- Open `DialectRulePack` bundling `packId` and verified rewrite rules together
with an anti-vacuity proof that every valid source unit has at least one
`EntryPre`-satisfying input. -/
structure DialectRulePack (Q Val Mem BlockRep : Type)
(UnitValid : BlockRep → Prop)
(EntryPre : BlockRep → Q → Prop)
(evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop) where
packId : Nat
rules : List (DialectRuleSpec Q Val Mem BlockRep EntryPre evalBlock)
entryInhabit : ∀ src, UnitValid src → ∃ q : Q, EntryPre src q
/-- Every valid source unit admitted to `pack` has an inhabited `EntryPre`. -/
theorem dialectRulePack_entry_inhabited {Q Val Mem BlockRep : Type}
{UnitValid : BlockRep → Prop}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop}
(pack : DialectRulePack Q Val Mem BlockRep UnitValid EntryPre evalBlock)
{src : BlockRep} (hValid : UnitValid src) :
∃ q : Q, EntryPre src q :=
pack.entryInhabit src hValid
/-- Look up and execute rule `ruleId` from `rules` (`List.foldr`, `0`
`._unsafe_rec`). -/
@[expose] def checkDialectRuleById {Q Val Mem BlockRep : Type}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop}
(rules : List (DialectRuleSpec Q Val Mem BlockRep EntryPre evalBlock))
(ruleId : Nat) (src tgt : BlockRep) : Bool :=
List.foldr
(fun r acc =>
match Nat.beq r.ruleId ruleId with
| true => r.checkApply src tgt
| false => acc)
false rules
theorem checkDialectRuleById_sound {Q Val Mem BlockRep : Type}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop} :
∀ (rules : List (DialectRuleSpec Q Val Mem BlockRep EntryPre evalBlock))
(ruleId : Nat) (src tgt : BlockRep),
checkDialectRuleById rules ruleId src tgt = true →
SemRefinesUnder (EntryPre src) (evalBlock src) (evalBlock tgt)
| [], _, _, _, h => by cases h
| r :: rs, ruleId, src, tgt, h => by
dsimp only [checkDialectRuleById, List.foldr] at h
cases hId : Nat.beq r.ruleId ruleId with
| true =>
rw [hId] at h
exact r.sound src tgt h
| false =>
rw [hId] at h
exact checkDialectRuleById_sound rs ruleId src tgt h
/-- Witness step selecting `(packId, ruleId)` and intermediate `BlockRep`. -/
structure RuleStepWitness (BlockRep : Type) where
packId : Nat
ruleId : Nat
next : BlockRep
/-- Check a bounded chain of `RuleStepWitness` rewrites from `cur0` ending at
`tgt` (`List.foldr`, `0` `._unsafe_rec`). -/
@[expose] def checkDialectRuleChain {Q Val Mem BlockRep : Type}
{UnitValid : BlockRep → Prop}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop}
(pack : DialectRulePack Q Val Mem BlockRep UnitValid EntryPre evalBlock)
(beqRep : BlockRep → BlockRep → Bool)
(steps0 : List (RuleStepWitness BlockRep))
(cur0 tgt : BlockRep) : Bool :=
List.foldr
(fun st ih cur =>
Nat.beq st.packId pack.packId &&
checkDialectRuleById pack.rules st.ruleId cur st.next &&
ih st.next)
(fun cur => beqRep cur tgt)
steps0 cur0
theorem checkDialectRuleChain_sound {Q Val Mem BlockRep : Type}
{UnitValid : BlockRep → Prop}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop}
(pack : DialectRulePack Q Val Mem BlockRep UnitValid EntryPre evalBlock)
(beqRep : BlockRep → BlockRep → Bool)
(hBeq : ∀ a b, beqRep a b = true → a = b)
(hValidKeep : ∀ a b rId,
checkDialectRuleById pack.rules rId a b = true →
UnitValid a → UnitValid b)
(hPreKeep : ∀ a b rId,
checkDialectRuleById pack.rules rId a b = true →
∀ q, EntryPre a q → EntryPre b q) :
∀ (steps : List (RuleStepWitness BlockRep)) (cur tgt : BlockRep),
UnitValid cur →
checkDialectRuleChain pack beqRep steps cur tgt = true →
UnitValid tgt ∧
SemRefinesUnder (EntryPre cur) (evalBlock cur) (evalBlock tgt)
| [], cur, tgt, hVal, h => by
have hEq : cur = tgt := hBeq cur tgt h
rw [← hEq]
exact ⟨hVal, fun _ _ hNoUb => ⟨hNoUb, fun _ hOut => hOut⟩⟩
| st :: sts, cur, tgt, hVal, h => by
have hRest := bool_and_right h
have hLeft := bool_and_left h
have hRule := bool_and_right hLeft
have hValMid : UnitValid st.next :=
hValidKeep cur st.next st.ruleId hRule hVal
have hRef1 :=
checkDialectRuleById_sound pack.rules st.ruleId cur st.next hRule
have ⟨hValTgt, hRef2⟩ :=
checkDialectRuleChain_sound pack beqRep hBeq hValidKeep hPreKeep sts
st.next tgt hValMid hRest
refine ⟨hValTgt, ?_⟩
intro q hEntry hNoUb
have ⟨hMidNoUb, hMidSub⟩ := hRef1 q hEntry hNoUb
have hEntryNext : EntryPre st.next q :=
hPreKeep cur st.next st.ruleId hRule q hEntry
have ⟨hTgtNoUb, hTgtSub⟩ := hRef2 q hEntryNext hMidNoUb
exact ⟨hTgtNoUb, fun out hOut => hMidSub out (hTgtSub out hOut)⟩
/-- Turn-key `CertifiedGate` over a `DialectRulePack`: enforces `maxSteps`
witness cap and proves `UnitValid tgt ∧ SemRefinesUnder (EntryPre src) ...` so
the gate plugs directly into `Anneal.Backend.composePassGates` as `g1` or `g2`
and into `liftContractAlongRefinement`. -/
@[expose] def mkDialectRulePackGate {Q Val Mem BlockRep : Type}
{UnitValid : BlockRep → Prop}
{EntryPre : BlockRep → Q → Prop}
{evalBlock : BlockRep → Q → ExecOutcome Val Mem → Prop}
(pack : DialectRulePack Q Val Mem BlockRep UnitValid EntryPre evalBlock)
(maxSteps : BlockRep → Nat)
(beqRep : BlockRep → BlockRep → Bool)
(hBeq : ∀ a b, beqRep a b = true → a = b)
(hValidKeep : ∀ a b rId,
checkDialectRuleById pack.rules rId a b = true →
UnitValid a → UnitValid b)
(hPreKeep : ∀ a b rId,
checkDialectRuleById pack.rules rId a b = true →
∀ q, EntryPre a q → EntryPre b q) :
CertifiedGate BlockRep BlockRep (List (RuleStepWitness BlockRep))
UnitValid
(fun src tgt =>
UnitValid tgt ∧
SemRefinesUnder (EntryPre src) (evalBlock src) (evalBlock tgt)) where
maxWitness := maxSteps
wSize := List.length
check := fun src tgt steps =>
checkDialectRuleChain pack beqRep steps src tgt
sound := fun src tgt steps hValid _ hChk =>
checkDialectRuleChain_sound pack beqRep hBeq hValidKeep hPreKeep steps src
tgt hValid hChk
end Anneal.Hybrid.ExtGateKit
end