This page lists the example methods and proofs shipped in the repository and what each theorem
establishes. Read it to find a complete proof close to the method you want to verify. The C#
sources are under Examples/Assembly, the F# sources under Examples/FSharp and the proofs under
Examples/Proofs. Build, extract and verify one as in getting started:
dotnet build Examples/Assembly -c Release
leancil extract Examples/Assembly/bin/Examples.dll "Loops::Countdown(uint)" artifacts/Countdown
leancil verify artifacts/Countdown --proof Examples/Proofs/Countdown.leanSentences about what a suite checks describe the repository's own tests
(dotnet run --file scripts/Test.cs -- --suite <name>, see validation). Those
sentences name the wrong implementations that each unchanged proof rejects.
When a suite pairs a proved contract with a counterexample, Lean checks the exact statement
of the positive proof against the refutation in the changed assembly. For example,
the reference-array length contract requires a live array to return its length with memory
unchanged and a null array to raise NullReferenceException. A compiled variant returns zero
on null. Weakening the live-array clause also changes the statement and invalidates that pairing.
Add, Choose, GenericIdentity, Struct, Countdown and CountCalls each name their
contract (addContract, chooseContract, identityContract, structContract,
countdownContract, countCallsContract) and prove its Holds as holds, alongside the
correctness theorem described below. Each refutation of a mutant states that contract's
Refuted: WrongAdd.lean restates addContract, and the suites build each other refutation
from the definition in the example file. Verification accepts a refutation only when the kernel
accepts it at the counterexample predicate of the example's holds statement. A contract
changed in the example therefore rejects a refutation of the contract it replaced; the
contracts suite checks this by narrowing chooseContract to empty memory.
Add: universal modular arithmetic correctness in the specified empty initial memory, andaddContract: the wrapping sum for every caller memory, which is left unchanged.AddModel: carries a theorem about a pure Lean model to the compiledAddthrough one theorem that the method returns the model's result, without re-proving the model theorem.DecodedAdd: theAddcontract for the programExtraction.decodedProgram?reads from the extraction's body bytes, proved by evaluating the decoded method without the translator's output. Its instruction-region proof states the stack result ofaddat pc 2 and preserves the frame and memory.CheckedArithmetic.AddandAdd64return the unsigned sum whenever it fits and preserve arbitrary caller memory. The 64-bit proof also holds with NOPs inserted before each instruction. In each width, replacing addition with subtraction returns one for inputs two and one. The verifier certifies that result as a counterexample to the contract, which requires three.Choose: universal checked selection for both Boolean inputs and every pair of 64-bit values, preserving arbitrary caller memory exactly.GenericIdentity: universal identity through direct, repeated and nested generic calls in C#, and a compiled F# identity wrapper, preserving arbitrary caller memory exactly.Loops.Countdown: universal termination and a zero result for everyuint, including zero anduint.MaxValue, using a decreasing natural-number measure over checked local storage.Loops.Drain: universal termination of a reassignedReadOnlySpan<int>parameter, returning zero after repeated slicing and preserving arbitrary caller memory exactly.Loops.AllZeroandLoops.Sum: an early-exit predicate and a wrapping fold over the symbolic contents of an arbitrary-lengthReadOnlySpan<uint>orReadOnlySpan<ulong>.Calls: a managed-call chain with an address-taken mutable local.CallsSummary:Callsfor every input over well-formed caller memory, returningx + 3and keeping all memory below its entry, proved once by steppingIncrementand the byrefMutateand once from aDecodedSummaryof each.IdentitySummaryandRepeatedSummary: the identity ofGenericIdentityforIdentity64andRepeated, proved once by steppingIdentity<ulong>and once from aDecodedSummaryof it that each call applies without stepping its body. Each file also proves that every call names the metadata token and type arguments the summary is bound to (decoded summaries).CountCallsSummary:Loops.CountCallsreturns its input for everyuint, proved once by steppingDecrementat the call of each iteration and once from aDecodedSummaryofDecrementthatcil_loop_callapplies at that call. The file also proves that every summary of the index the call enters is bound to the token ofDecrement, and refutes one bound to the token ofCountCalls.VectorSummary:DivisionIntrinsics.UnsafeLowNextreturns its input plus one for everyulong, proved once by steppingUnsafeLow, whoseVector128.CreateScalarUnsafeandGetElementcalls run through their runtime models, and once from aDecodedSummaryofUnsafeLowthat the call applies without stepping its body. The summary's type lists both runtime models, and the caller discharges them from the extraction's model facts.IntegerOperations.Negate32/Negate64: checked-execution proofs that negation returns the modular additive inverse for every input, including the signed minimum.NarrowIntegers: signed/unsigned casts, character values, calls and an eight-byte struct containing narrow fields.UnsignedShort.leanproves reduction modulo 65,536 for every 32-bit input.PrimitiveOperations: reads/writes through integer references, aliasing, switch tables and aggregatesizeof.PrimitiveReadWrite.leanproves that a store followed by a load returns every 32-bit input unchanged.Alias: two arguments naming the same caller storage.Struct: universal return of the input through a 12-byte explicit-layout struct, initialization, two field stores and a byref helper call. For every well-formed caller memory, all earlier allocation metadata, bytes and access permissions are preserved; temporary frame allocations are expired on return. The proof tracks the struct local inLocalSnapshotsand steps field stores and loads decoded from the layout rather than through bytes.StructCopyseparately checks by-value use of the same layout.LargeStruct: a 40-byte explicit layout with a field at offset 32.PastEnd: a permitted end sentinel whose dereference is rejected as outside the allocation, for every fuel budget.Escape: a reference to an expired local is rejected on return, for every fuel budget.WrongAdd: a verified refutation ofaddContractfromAdd.leanat inputs(0, 1).- A separate
Examples.Hardwareassembly, built from the file-based libraryExamples/Hardware/Hardware.cs, tests runtime capability extraction. - A Cecil-generated independent fixture tests extraction-bound static RVA bytes.
StaticSpansreads a 16-byteReadOnlySpan<byte>lookup table; out-of-bounds reads, writes and tampered RVA bytes are checked.StaticValuesloadsWord256.Zero,OneandMinValue, fixed by implicit conversions in the static constructor, proves their limbs and stores them through an out parameter;MaxValue, writes and stores outside the static constructor are rejected.SeededHashmixes a value with twostatic readonly ulongseeds drawn fromRandomNumberGenerator;OpaqueSeeds.leanproves the hash for every seed pair and that a fixed seed is not the contract.SpanTablesindexesReadOnlySpan<uint>andReadOnlySpan<ulong>tables, reads a length and the first element, and faults withSystem.IndexOutOfRangeExceptionout of range.WordReader.Readconsumes a word from a caller-supplied array: a helper advancesPosition, the caller decrementsRemaining, then reads the element. Its completed outline proves the returned element and cursor consumption for a nonempty remaining range withPosition + Remainingequal to the array length and length below2^32. The theorem assumes valid array contents, field write authority and separation of the array from the cursor fields.SkipAndPeekconsumes one position and reads the following word, requiring at least two remaining words; its bound is proved after the cursor update.ReadSavedkeeps the remaining count across a call toReserve, which returns the saved position, then reads that position. Its consumption contract matchesRead.ReplaceRemainingpreserves the old range end through a helper with private locals before replacing the count. Outside the stated assumptions, an invalid read can throw after bookkeeping has changed.ItemPool.Rentreuses the head of an intrusive free list.PoolRent.leanproves that it returns that head, advances the list past it, clears its link, decrements the idle count and marks it rented, writing no other field, and under the class catalog premise leaves the live count unchanged; with an empty list and room under the capacity it creates an item owned by the pool, numbered with the next id and marked rented; an exhausted pool runs the CoreLibInvalidOperationException(string)constructor on its bound message literal, given heap room for the exception, and throws it, and a null pool throwsNullReferenceException. Its object sites agree with the catalog, so the premise stated at entry holds after any invocation of the program.ItemPool.IsIdlewalks the free list through an object local.PoolIdle.leantakes the list as aSegmentto null visitingnodes, whose length is the loop's measure, and proves that the method answers whether the item is one ofnodes, for a null or any live item, and writes nothing.NullReferencestestsUnsafe.NullRef<T>withUnsafe.IsNullRef<T>, faults on loads, stores and field accesses through it, and selects an optionalrefargument that is either unset or bound, as optional outputs do.VirtualCallscalls an abstract and a defaulted virtual method ofAnimalon any animal:AnimalLegs.leanandAnimalLoudness.leanprove the override or inherited body the receiver's runtime class selects, the null receiver'sNullReferenceException, and that a class outside the extraction faults rather than returning;FreshDogLegs.leandispatches on a constructed instance.ClassTeststests and casts an animal:DogTest.leanprovesanimal is Dogfor aDog, aBirdand null, andDogCast.leanproves that(Dog)animalreturns aDogand null unchanged and throwsInvalidCastExceptionfor aBird.Stringspasses, stores and returns strings as opaque references (StringValues.lean,StringLabel.lean).StringLiterals.leanproves two loads of one literal are one object, andStringDefault.leanproveslabel ?? "none"returns the label or the bound"none"object; both show an unbound literal stops as unsupported rather than loading null.Guardscalls the framework argument guards.GuardCount.leanprovesThrowIfNegativeraisesArgumentOutOfRangeExceptionexactly for a negative count,GuardIndex.leanproves the unsignedThrowIfGreaterThanOrEqualcompares as unsigned, andGuardRequired.leanprovesThrowIfNullraisesArgumentNullExceptionexactly for null. Replacing the compiled guard withThrowIfNegativeOrZeroraisesArgumentOutOfRangeExceptionat zero. The refutation certificate binds that counterexample to the changed entry and its assembly.
Concrete example proofs establish their displayed inputs. Only explicitly universally quantified
theorems claim arbitrary-input correctness. CheckedAdd64, Choose and GenericIdentity quantify
caller memory and prove it unchanged. Struct quantifies well-formed caller memory and proves
MemoryBelow preservation of the caller's storage. Other examples fix the caller memory to
CIL.Safety.Memory.empty or to the 8-byte callerMemory the file defines; argument quantification
alone does not imply arbitrary caller memory. The allocating generic instance wrapper retains a
separate fixed-memory check in GenericInstance.lean.
The Examples.Bits methods call the integer bit helpers such as PopCount, LeadingZeroCount,
TrailingZeroCount, Log2 and IsPow2, with universal proofs of the integer logarithm
and of a rotation round trip. Incorrect implementations fail the same contracts. Log2(0) returns
zero; rounding up returns zero for zero input or overflow; signed power-of-two checks reject
negative values.
Reachable backward branches and switch targets are admitted when control-flow targets and stack joins validate. Feature reachability uses a fixed point: a backedge that invalidates a constant fact causes affected instructions to be revisited. Recursive managed calls are not supported.
Extraction does not establish termination. The countdown proof
uses CIL.Safety.invoke_loop_satisfies, which applies loop_terminates_induction, with the measure
remaining.toNat and no invariant of its own: the loop state is a FrameState whose LoopFrame,
generated by bind_entry ... allocating, keeps the counter's home writable and its value known. The
loop head is found from the compiled branch instruction. cil_loop_recurse steps the path from
entry, and from each head with a nonzero count, to the next head and infers its execution cost; each
iteration proves a strictly smaller measure; cil_loop_finish proves the return of the zero case.
The rule composes this with frame entry into the CIL.Safety.Ensures obligation, so the theorem
supplies successful finite execution for every input, including the maximum 32-bit unsigned value,
without unrolling billions of iterations. Subtraction cannot underflow because it occurs only when
the counter is positive.
The loops suite checks the unchanged universal proof after inserting NOPs and rearranging basic
blocks, and requires it to reject both an incorrect result and a loop whose counter never
decreases.
The counted-loop proof shows that Loops.CountCalls returns
its input for every uint, counting iterations while a Decrement helper lowers the remaining
count. Each iteration crosses the call through decrementContract with loop_terminates_induction
and cil_loop_call, which names the returned count and keeps both locals of the generated frame
across the call through LoopFrame.after_confined; cil_loop_recurse stores them and steps back to
the head, and the invariant states only count + remaining = value. The suite verifies the
unchanged loop proof against a build whose helper computes value + 0xFFFFFFFF, re-proving only
the helper contract. It rejects a build that discards the helper result and refutes the counting
contract for a build that counts twice.
The struct-local loop proof shows that Loops.TallyTwice
returns twice its input for every uint and allocates nothing the caller sees. Its loop state is a
struct local remembered by its count and sum fields. The loop tactics zero and
store the struct, read its fields and cross the AddTwo call through its contract with the frame
facts they carry, and the proof supplies only the invariant sum = 2 * count, the measure and the
arithmetic.
The early-exit copy proof shows that Loops.CopyUntilZero
copies the words of a readonly span before its first zero to a caller buffer through its Stamp
helper, returns their count with bit 31 set exactly when a zero ended the copy, and changes no
caller byte outside the copied words, for every span length and contents and every output with write
authority over those words that lies apart from the span. The proof states the bindings, Stamp's
contract, the invariant and the measure: the loop tactics read the span in each frame memory from
its facts at the caller's memory, cross the call with the frame after it, and carry the buffer's
contents and write authority through every store and the return. The suite rejects builds whose
Stamp writes zero or whose loop copies past a zero.
The outcome loop proof shows that
Loops.CountUntil(value, limit) returns value when value <= limit, and otherwise propagates the
System.InvalidOperationException that its Bump helper throws once the count reaches limit,
after limit successful calls. The theorem holds for every pair of uints from empty caller
memory. The
proof uses only bumpContract, an OutcomeContract naming when Bump throws, through
loop_outcome_induction, cil_loop_outcome_call and cil_loop_outcome_raise;
ensures_outcome_of_loop gives the method's EnsuresOutcome. The suite verifies the unchanged
loop proof against a Bump that tests inequality and subtracts minus one, and rejects it at the
exceptional exit for a Bump that throws System.ArgumentException under a contract re-proved to
say so.
The buffer fill proof shows that Loops.FillWords, which
stores value through Unsafe.Add(ref destination, i) for each i < count, leaves
Contents final destination 8 (List.replicate count value) for every nonnegative int count and is
Confined to those 8 * count bytes. The theorem assumes only write authority over the words
(Writable). It does not assume readable or initialized contents. Its invariant is Filled: the
first i words are filled and the rest are still only writable. The loop state is a
FrameState, whose LoopFrame carries the footprint, well-formedness, index home and index value;
the proof writes the element through the frame and the loop tactics keep the rest. The suite
rejects builds that shift every store by one word or skip every other word.
The span predicate proof and the span fold
proof state their results over SpanContents, the library's
description of what a span holds. Loops.AllZero returns whether values.all (· == 0) and leaves
caller memory unchanged; Loops.Sum returns values.sum with wrapping ulong addition while a
frame home holds the running total, and keeps all memory below the caller's allocation watermark.
Both theorems hold for every length, including null empty spans. Each invariant relates the
remaining suffix to the answer (remaining.all (· == 0) = result,
total + remaining.sum = result), its measure is the suffix length, and CheckedSpan.head and
CheckedSpan.tail carry it across one values[0] read and values.Slice(1). Each proof states
its specification, invariant and measure, the next state of each iteration and the facts its steps
use; frame entry, the frame home and the exit's memory fact come from the loop verification
conditions. The suite rejects a build of
AllZero that replaces every read with zero and a build of Sum that stops while one element
remains.
Loop invariants and decreasing measures are supplied by the proof author. The loops suite
rejects an incorrect loop under the unchanged contract, checks malformed stack joins and changing
loop facts, and proves that an admitted infinite loop exhausts every fuel budget. Fuel exhaustion
is never successful verification of total correctness.
The F# examples demonstrate arithmetic, branching, real method
calls, byref mutation and mutable structs with constructors. They use the same CIL semantics,
extractor and Lean proof pipeline as the C# examples.
let Add (x: uint64) (y: uint64) = x + yVerify the compiled F# addition with the language-independent
addition contract, the proof the C# Add uses:
dotnet build Examples/FSharp -c Release
leancil extract Examples/FSharp/bin/Examples.FSharp.dll "Arithmetic::Add(ulong,ulong)" artifacts/FSharpAdd
leancil verify artifacts/FSharpAdd --proof Examples/Proofs/Add.leanThe theorem proves (x + y) mod 2^64 for every pair of 64-bit inputs. The fsharp suite also
checks universal store/load and constructor contracts. At inputs zero and one, the compiled
subtraction returns the largest unsigned word. The kernel checks this counterexample to addition.
These examples cover F# programs that compile into the supported CIL subset. F# lists, closures, discriminated unions and arbitrary FSharp.Core calls are not generally supported; the suite includes an explicitly rejected list example.
The GenericMethods module also demonstrates generic identity and selection functions. LeanCIL
specializes their compiled CIL for the concrete value types used by reachable calls. In a
specialized body, typeof(T) == typeof(Marker) and != become constants when both types are closed
and decided, as the JIT folds them, so a profile-dependent or marker-type branch is pruned like a
feature check. Lean recomputes each folded constant from the raw closed body; see type
tests for the exact pattern. Examples.TypeTests exercises a matching and a
non-matching type argument; the generics suite checks these examples. The F# and C# identity
examples share the same universal Lean contract:
leancil extract Examples/FSharp/bin/Examples.FSharp.dll "GenericMethods::Identity64(ulong)" artifacts/FSharpIdentity
leancil verify artifacts/FSharpIdentity --proof Examples/Proofs/GenericIdentity.lean