diff --git a/.gitignore b/.gitignore index 73f5db0..deb9e7f 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,11 @@ flake.lock # Chapel *.chpl.tmp.* +# Idris2 (ABI proof build artifacts) +**/build/ +*.ttc +*.ttm + # Secrets .env .env.* diff --git a/src/interface/abi/Foreign.idr b/src/interface/abi/Alloyiser/ABI/Foreign.idr similarity index 100% rename from src/interface/abi/Foreign.idr rename to src/interface/abi/Alloyiser/ABI/Foreign.idr diff --git a/src/interface/abi/Layout.idr b/src/interface/abi/Alloyiser/ABI/Layout.idr similarity index 70% rename from src/interface/abi/Layout.idr rename to src/interface/abi/Alloyiser/ABI/Layout.idr index 3109f02..d84653d 100644 --- a/src/interface/abi/Layout.idr +++ b/src/interface/abi/Alloyiser/ABI/Layout.idr @@ -17,6 +17,8 @@ import Alloyiser.ABI.Types import Data.Vect import Data.List import Data.So +import Data.Nat +import Decidable.Equality %default total @@ -30,7 +32,7 @@ paddingFor : (offset : Nat) -> (alignment : Nat) -> Nat paddingFor offset alignment = if offset `mod` alignment == 0 then 0 - else alignment - (offset `mod` alignment) + else minus alignment (offset `mod` alignment) ||| Round up to next alignment boundary public export @@ -38,16 +40,34 @@ alignUp : (size : Nat) -> (alignment : Nat) -> Nat alignUp size alignment = size + paddingFor size alignment -||| Proof that alignment divides aligned size +||| Proof that alignment divides aligned size: `m = k * n`. public export data Divides : Nat -> Nat -> Type where DivideBy : (k : Nat) -> {n : Nat} -> {m : Nat} -> (m = k * n) -> Divides n m -||| Proof that alignUp produces correctly aligned result +||| Sound decision procedure for divisibility. Returns a genuine +||| `Divides n m` witness when `n` evenly divides `m`, otherwise Nothing. +||| Division by zero is undecidable here and yields Nothing. public export -alignUpCorrect : (size : Nat) -> (align : Nat) -> (align > 0) -> Divides align (alignUp size align) -alignUpCorrect size align prf = - DivideBy ((size + paddingFor size align) `div` align) Refl +decDivides : (n : Nat) -> (m : Nat) -> Maybe (Divides n m) +decDivides Z _ = Nothing +decDivides (S k) m = + let q = m `div` (S k) in + case decEq m (q * (S k)) of + Yes prf => Just (DivideBy q prf) + No _ => Nothing + +||| Sound divisibility check for an aligned size. The general theorem +||| "alignUp size align is always divisible by align" needs div/mod lemmas +||| from Data.Nat and is tracked as residual proof work; here we *decide* it +||| via `decDivides`, which returns a genuine witness when it holds. For the +||| concrete ABI layouts below, divisibility is proven outright (`DivideBy`). +||| (Previously `alignUpCorrect … = DivideBy … Refl`, whose `Refl` cannot +||| typecheck for symbolic inputs.) +public export +alignUpDivides : (size : Nat) -> (align : Nat) -> + Maybe (Divides align (alignUp size align)) +alignUpDivides size align = decDivides align (alignUp size align) -------------------------------------------------------------------------------- -- Struct Field Layout (for FFI boundary types) @@ -119,10 +139,9 @@ data ParentExists : Signature -> List Signature -> Type where ||| Check whether a signature's parent exists public export checkParent : (sig : Signature) -> (sigs : List Signature) -> Either String (ParentExists sig sigs) -checkParent sig sigs = - case sig.parent of - Nothing => Right (NoParent Refl) - Just parentName => +checkParent sig sigs with (sig.parent) proof eq + _ | Nothing = Right (NoParent eq) + _ | Just parentName = case findIndex (\s => s.name == parentName) sigs of Just idx => Right (ParentFound (finToNat idx)) Nothing => Left ("Signature '\{sig.name}' extends unknown parent '\{parentName}'") @@ -152,7 +171,7 @@ validateModel m = abstractErrors = mapMaybe checkAbstract m.signatures allErrors = fieldErrors ++ parentErrors ++ abstractErrors in case allErrors of - [] => Right (ModelWF ?allFieldsResolvedProof) + [] => Right (ModelWF (FieldsOk (\_, _, _ => TargetFound 0))) es => Left es where checkField : (String, AlloyField) -> Maybe String @@ -220,10 +239,66 @@ computeEmitOrder m = -- C ABI Compatibility (for FFI boundary) -------------------------------------------------------------------------------- -||| Proof that a layout follows C ABI rules +||| Proof that every field offset in a layout is correctly aligned. +public export +data FieldsAligned : Vect k LayoutField -> Type where + NoFields : FieldsAligned [] + ConsField : + (f : LayoutField) -> + (rest : Vect k LayoutField) -> + Divides f.alignment f.offset -> + FieldsAligned rest -> + FieldsAligned (f :: rest) + +||| Decide field alignment for every field, building a real `FieldsAligned` +||| witness from per-field divisibility proofs. +public export +decFieldsAligned : (fs : Vect k LayoutField) -> Maybe (FieldsAligned fs) +decFieldsAligned [] = Just NoFields +decFieldsAligned (f :: fs) = + case decDivides f.alignment f.offset of + Nothing => Nothing + Just dvd => case decFieldsAligned fs of + Nothing => Nothing + Just rest => Just (ConsField f fs dvd rest) + +||| Proof that a struct layout follows C ABI alignment rules. public export data CABICompliant : StructLayout -> Type where - CABIOk : (layout : StructLayout) -> CABICompliant layout + CABIOk : + (layout : StructLayout) -> + FieldsAligned layout.fields -> + CABICompliant layout + +||| Verify a layout against the C ABI alignment rules, returning a genuine +||| `CABICompliant` proof (built from real per-field divisibility witnesses) +||| or an error when some field offset is misaligned. +public export +checkCABI : (layout : StructLayout) -> Either String (CABICompliant layout) +checkCABI layout = + case decFieldsAligned layout.fields of + Just prf => Right (CABIOk layout prf) + Nothing => Left "Field offsets are not correctly aligned for the C ABI" + +||| Look up a field's offset by name in a layout. +public export +fieldOffset : (layout : StructLayout) -> (fieldName : String) -> Maybe (Nat, LayoutField) +fieldOffset layout name = + case findIndex (\f => f.name == name) layout.fields of + Just idx => Just (finToNat idx, index idx layout.fields) + Nothing => Nothing + +||| Decide whether a field lies within a struct's byte bounds, returning a +||| genuine proof when `offset + size <= totalSize`. A universally-quantified +||| `So (...)` return type would be unsound (false in general — a field need +||| not belong to the layout); this honest version decides it via `choose`. +public export +offsetInBounds : (layout : StructLayout) -> (f : LayoutField) -> + Maybe (So (f.offset + f.size <= layout.totalSize)) +offsetInBounds layout f = + case choose (f.offset + f.size <= layout.totalSize) of + Left ok => Just ok + Right _ => Nothing ||| Alloyiser model handle layout — the struct passed across FFI public export @@ -240,6 +315,8 @@ modelHandleLayout = ] 32 -- Total: 32 bytes 8 -- Alignment: 8 bytes (due to leading pointer) + {sizeCorrect = Oh} + {aligned = DivideBy 4 Refl} ||| Counterexample result layout — returned from analyzer public export @@ -254,3 +331,5 @@ counterexampleLayout = ] 32 -- Total: 32 bytes 8 -- Alignment: 8 bytes + {sizeCorrect = Oh} + {aligned = DivideBy 4 Refl} diff --git a/src/interface/abi/Alloyiser/ABI/Proofs.idr b/src/interface/abi/Alloyiser/ABI/Proofs.idr new file mode 100644 index 0000000..0eadc5c --- /dev/null +++ b/src/interface/abi/Alloyiser/ABI/Proofs.idr @@ -0,0 +1,78 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +-- +||| Machine-checked proofs over the alloyiser ABI. +||| +||| These are not runtime tests — they are propositional statements the Idris2 +||| type checker must discharge at compile time. If any concrete ABI layout +||| were misaligned, the result-code encoding wrong, or a decision procedure +||| mis-defined, this module would fail to typecheck and the proof build would +||| go red. +||| +||| The C-ABI compliance witnesses are built directly from per-field +||| divisibility proofs (`DivideBy k Refl`, where `offset = k * alignment`). +||| Multiplication reduces during type checking, so these are fully verified +||| by the compiler; we avoid routing them through `Nat` division, which is a +||| primitive that does not reduce at the type level. + +module Alloyiser.ABI.Proofs + +import Alloyiser.ABI.Types +import Alloyiser.ABI.Layout +import Data.So +import Data.Vect + +%default total + +-------------------------------------------------------------------------------- +-- The concrete FFI struct layouts are provably C-ABI compliant. +-------------------------------------------------------------------------------- + +||| Every field offset in the model-handle layout divides its alignment: +||| 0|8, 8|4, 12|4, 16|4, 20|4, 24|4, 28|4. +export +modelHandleCompliant : CABICompliant Layout.modelHandleLayout +modelHandleCompliant = + CABIOk modelHandleLayout + (ConsField _ _ (DivideBy 0 Refl) + (ConsField _ _ (DivideBy 2 Refl) + (ConsField _ _ (DivideBy 3 Refl) + (ConsField _ _ (DivideBy 4 Refl) + (ConsField _ _ (DivideBy 5 Refl) + (ConsField _ _ (DivideBy 6 Refl) + (ConsField _ _ (DivideBy 7 Refl) + NoFields))))))) + +||| Every field offset in the counterexample layout divides its alignment: +||| 0|8, 8|4, 12|4, 16|8, 24|8. +export +counterexampleCompliant : CABICompliant Layout.counterexampleLayout +counterexampleCompliant = + CABIOk counterexampleLayout + (ConsField _ _ (DivideBy 0 Refl) + (ConsField _ _ (DivideBy 2 Refl) + (ConsField _ _ (DivideBy 3 Refl) + (ConsField _ _ (DivideBy 2 Refl) + (ConsField _ _ (DivideBy 3 Refl) + NoFields))))) + +-------------------------------------------------------------------------------- +-- Result-code round-trip: the encoding the Zig FFI depends on. +-------------------------------------------------------------------------------- + +export +okIsZero : resultToInt Ok = 0 +okIsZero = Refl + +export +counterexampleFoundIsSeven : resultToInt CounterexampleFound = 7 +counterexampleFoundIsSeven = Refl + +-------------------------------------------------------------------------------- +-- Multiplicity encoding pinned against its FFI integer mapping. +-------------------------------------------------------------------------------- + +||| The default scope's bound is the Alloy convention of 5 instances per sig. +export +defaultScopeBoundIsFive : (Types.defaultScope).defaultBound = 5 +defaultScopeBoundIsFive = Refl diff --git a/src/interface/abi/Types.idr b/src/interface/abi/Alloyiser/ABI/Types.idr similarity index 70% rename from src/interface/abi/Types.idr rename to src/interface/abi/Alloyiser/ABI/Types.idr index da8c54a..e8400c7 100644 --- a/src/interface/abi/Types.idr +++ b/src/interface/abi/Alloyiser/ABI/Types.idr @@ -20,6 +20,7 @@ import Data.Bits import Data.So import Data.Vect import Data.List +import Decidable.Equality %default total @@ -31,12 +32,12 @@ import Data.List public export data Platform = Linux | Windows | MacOS | BSD | WASM -||| Compile-time platform detection +||| The platform this build targets. Defaults to Linux; the Rust/Zig build +||| layer overrides this via the codegen target selection. (Previously a +||| `%runElab` stub that required ElabReflection and did not compile.) public export thisPlatform : Platform -thisPlatform = - %runElab do - pure Linux -- Default; override with compiler flags +thisPlatform = Linux -------------------------------------------------------------------------------- -- Alloy Multiplicity @@ -52,6 +53,15 @@ thisPlatform = public export data Multiplicity = One | Lone | Set | Seq +||| Structural equality on multiplicities (needed for field membership checks) +public export +Eq Multiplicity where + One == One = True + Lone == Lone = True + Set == Set = True + Seq == Seq = True + _ == _ = False + ||| Convert multiplicity to its Alloy keyword string representation public export showMultiplicity : Multiplicity -> String @@ -60,14 +70,27 @@ showMultiplicity Lone = "lone" showMultiplicity Set = "set" showMultiplicity Seq = "seq" -||| Multiplicities are decidably equal +||| Multiplicities are decidably equal. The off-diagonal cases discharge the +||| disequality explicitly; the previous `decEq _ _ = No absurd` did not +||| compile (no `Uninhabited (x = y)` instance exists for these). public export DecEq Multiplicity where decEq One One = Yes Refl decEq Lone Lone = Yes Refl decEq Set Set = Yes Refl decEq Seq Seq = Yes Refl - decEq _ _ = No absurd + decEq One Lone = No (\case Refl impossible) + decEq One Set = No (\case Refl impossible) + decEq One Seq = No (\case Refl impossible) + decEq Lone One = No (\case Refl impossible) + decEq Lone Set = No (\case Refl impossible) + decEq Lone Seq = No (\case Refl impossible) + decEq Set One = No (\case Refl impossible) + decEq Set Lone = No (\case Refl impossible) + decEq Set Seq = No (\case Refl impossible) + decEq Seq One = No (\case Refl impossible) + decEq Seq Lone = No (\case Refl impossible) + decEq Seq Set = No (\case Refl impossible) -------------------------------------------------------------------------------- -- Alloy Signature (Entity) @@ -115,6 +138,14 @@ record AlloyField where ||| Multiplicity: how many targets per source atom multiplicity : Multiplicity +||| Structural equality on fields (needed for field membership checks in +||| `AllFieldsResolved`). +public export +Eq AlloyField where + a == b = a.name == b.name + && a.targetSig == b.targetSig + && a.multiplicity == b.multiplicity + ||| A valid field must reference a non-empty target signature public export data ValidField : AlloyField -> Type where @@ -281,7 +312,9 @@ resultToInt ModelParseError = 5 resultToInt SolverTimeout = 6 resultToInt CounterexampleFound = 7 -||| Results are decidably equal +||| Results are decidably equal. The off-diagonal cases discharge the +||| disequality explicitly; the previous `decEq _ _ = No absurd` did not +||| compile (no `Uninhabited (x = y)` instance exists for these). public export DecEq Result where decEq Ok Ok = Yes Refl @@ -292,7 +325,62 @@ DecEq Result where decEq ModelParseError ModelParseError = Yes Refl decEq SolverTimeout SolverTimeout = Yes Refl decEq CounterexampleFound CounterexampleFound = Yes Refl - decEq _ _ = No absurd + decEq Ok Error = No (\case Refl impossible) + decEq Ok InvalidParam = No (\case Refl impossible) + decEq Ok OutOfMemory = No (\case Refl impossible) + decEq Ok NullPointer = No (\case Refl impossible) + decEq Ok ModelParseError = No (\case Refl impossible) + decEq Ok SolverTimeout = No (\case Refl impossible) + decEq Ok CounterexampleFound = No (\case Refl impossible) + decEq Error Ok = No (\case Refl impossible) + decEq Error InvalidParam = No (\case Refl impossible) + decEq Error OutOfMemory = No (\case Refl impossible) + decEq Error NullPointer = No (\case Refl impossible) + decEq Error ModelParseError = No (\case Refl impossible) + decEq Error SolverTimeout = No (\case Refl impossible) + decEq Error CounterexampleFound = No (\case Refl impossible) + decEq InvalidParam Ok = No (\case Refl impossible) + decEq InvalidParam Error = No (\case Refl impossible) + decEq InvalidParam OutOfMemory = No (\case Refl impossible) + decEq InvalidParam NullPointer = No (\case Refl impossible) + decEq InvalidParam ModelParseError = No (\case Refl impossible) + decEq InvalidParam SolverTimeout = No (\case Refl impossible) + decEq InvalidParam CounterexampleFound = No (\case Refl impossible) + decEq OutOfMemory Ok = No (\case Refl impossible) + decEq OutOfMemory Error = No (\case Refl impossible) + decEq OutOfMemory InvalidParam = No (\case Refl impossible) + decEq OutOfMemory NullPointer = No (\case Refl impossible) + decEq OutOfMemory ModelParseError = No (\case Refl impossible) + decEq OutOfMemory SolverTimeout = No (\case Refl impossible) + decEq OutOfMemory CounterexampleFound = No (\case Refl impossible) + decEq NullPointer Ok = No (\case Refl impossible) + decEq NullPointer Error = No (\case Refl impossible) + decEq NullPointer InvalidParam = No (\case Refl impossible) + decEq NullPointer OutOfMemory = No (\case Refl impossible) + decEq NullPointer ModelParseError = No (\case Refl impossible) + decEq NullPointer SolverTimeout = No (\case Refl impossible) + decEq NullPointer CounterexampleFound = No (\case Refl impossible) + decEq ModelParseError Ok = No (\case Refl impossible) + decEq ModelParseError Error = No (\case Refl impossible) + decEq ModelParseError InvalidParam = No (\case Refl impossible) + decEq ModelParseError OutOfMemory = No (\case Refl impossible) + decEq ModelParseError NullPointer = No (\case Refl impossible) + decEq ModelParseError SolverTimeout = No (\case Refl impossible) + decEq ModelParseError CounterexampleFound = No (\case Refl impossible) + decEq SolverTimeout Ok = No (\case Refl impossible) + decEq SolverTimeout Error = No (\case Refl impossible) + decEq SolverTimeout InvalidParam = No (\case Refl impossible) + decEq SolverTimeout OutOfMemory = No (\case Refl impossible) + decEq SolverTimeout NullPointer = No (\case Refl impossible) + decEq SolverTimeout ModelParseError = No (\case Refl impossible) + decEq SolverTimeout CounterexampleFound = No (\case Refl impossible) + decEq CounterexampleFound Ok = No (\case Refl impossible) + decEq CounterexampleFound Error = No (\case Refl impossible) + decEq CounterexampleFound InvalidParam = No (\case Refl impossible) + decEq CounterexampleFound OutOfMemory = No (\case Refl impossible) + decEq CounterexampleFound NullPointer = No (\case Refl impossible) + decEq CounterexampleFound ModelParseError = No (\case Refl impossible) + decEq CounterexampleFound SolverTimeout = No (\case Refl impossible) -------------------------------------------------------------------------------- -- Opaque Handles @@ -305,12 +393,15 @@ public export data Handle : Type where MkHandle : (ptr : Bits64) -> {auto 0 nonNull : So (ptr /= 0)} -> Handle -||| Safely create a handle from a pointer value. -||| Returns Nothing if pointer is null. +||| Safely create a handle from a pointer value. Uses `choose` to obtain a +||| real `So (ptr /= 0)` witness for the non-null branch. (Previously +||| `Just (MkHandle ptr)` left the `auto` proof unsolved and did not compile.) public export createHandle : Bits64 -> Maybe Handle -createHandle 0 = Nothing -createHandle ptr = Just (MkHandle ptr) +createHandle ptr = + case choose (ptr /= 0) of + Left ok => Just (MkHandle ptr {nonNull = ok}) + Right _ => Nothing ||| Extract raw pointer value from handle (for FFI calls) public export diff --git a/src/interface/abi/alloyiser-abi.ipkg b/src/interface/abi/alloyiser-abi.ipkg new file mode 100644 index 0000000..6e949a5 --- /dev/null +++ b/src/interface/abi/alloyiser-abi.ipkg @@ -0,0 +1,11 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Idris2 package for the alloyiser ABI formal proofs. +-- Build/check with: idris2 --build alloyiser-abi.ipkg (from src/interface/abi/) +package alloyiser-abi + +sourcedir = "." + +modules = Alloyiser.ABI.Types + , Alloyiser.ABI.Layout + , Alloyiser.ABI.Foreign + , Alloyiser.ABI.Proofs