A lot of people are now interested in software verification, both because AI is finding many bugs, and because AI is lowering the barrier to entry to formal methods. I believe the future of verification is proof-oriented programming, a term I take from F*. A core element of proof-oriented programming is that a system’s specification can be proven directly about its implementation. As of November 2026, there are two proof-oriented programming languages that seem poised to catch on: Verus and Lean. This post describes a small case study which illustrates the contrasts between the two approaches.
A common issue with verification tools is that they can verify a model of your system, but not the system itself. For example, one can model the correctness of a consensus protocol like Raft in TLA+, but TLA+ cannot check that a Rust implementation of Raft is written correctly. There are plenty of workarounds like differential testing, but hopefully the future does not consist solely of workarounds.
Specifically, we’re going to implement a verified bitset. A bitset is an efficient data structure for sets of numbers over a small fixed domain. For example, say we want a set which can contain the numbers 0 to 127. We can represent that set as two 64-bit integers. To insert the number 5, we set the 5th bit on the first integer to a 1. Operations like set union reduce to bit operations like bitwise-OR.
Bitsets are a nice case study because their implementation is small and self-contained, and their specification is straightforward: a bitset should behave like a “normal” or “abstract” set. Moreover, neither Verus nor Lean appears to have a bitset implementation, so it was a fun exercise for me! For context, I know a lot about Rust, a moderate amount about Lean, and very little about Verus. I apologize in advance for errors or unnecessarily complex proofs. All code in this post is publicly available at willcrichton/verified-bitset.
AI disclosure: The text of this post was written entirely by hand. I largely wrote the specifications by hand with light AI assistance. I used AI heavily to generate the proof terms.
A bitset is defined by a domain, or the maximum number of
elements in the set. The bitset contains an array of fixed-size
integers, for simplicity always 64-bit. This array needs
⌈domain / 64⌉ words. We’ll look at the Verus definition on
the left, and the Lean definition on the right (or top / bottom on
mobile).
struct Bitset {
words: Vec<u64>,
domain: usize
}
impl Bitset {
#[vstd::contrib::auto_spec]
fn num_words(d: usize) -> usize {
d / 64 + if d % 64 != 0 { 1 } else { 0 }
}
}abbrev Bitset.numWords (d : Nat) : Nat :=
(d + 63) / 64
structure Bitset (d : Nat) where
words : Vector UInt64 (Bitset.numWords d)
-- ...One difference is that the domain is encoded as a field in Rust and
as a type parameter in Lean. The type parameter encoding seems like the
most proof-oriented design, because the field words carries
its length numWords d in its type (i.e., it is
intrinsically verified). But the field encoding is idiomatic
for Rust, and a type parameter would not work as expected — a type such
as [u64; num_words(d)] is currently unstable in Rust and
unsupported in Verus (we thus must use extrinsic
verification).
Another difference is that the Rust words array contains
unboxed integers, while in Lean, words will box each word
individually. We would need to use a specialized type of unboxed integer
arrays in Lean to get memory-parity with Rust.
The num_words implementation in Rust is more complex
than Lean in two ways. First is auto_spec, which we will
discuss shortly. Second is the idiosyncratic implementation of ceiling
division. In Rust, the domain is a usize, meaning it can
overflow (which Verus categorically prevents). The expression
(d + 63) / 64 overflows for
d > usize::MAX - 63. This is not an issue in Lean
because most arithmetic happens on natural numbers (Nat)
which have unbounded size.
div_ceil?
A seasoned Rust programmer might observe that div_ceil
is exactly the function we want. The problem is that as of the time of
writing, the Verus standard library does not provide a formal semantics
for div_ceil. We could in theory provide one ourselves, but
I don’t want to make this post more complicated than it already is!
The last difference is how we encode data structure invariants. Bitsets have two key invariants:
is_subset method
correct.)impl Bitset {
pub closed spec fn wf(self) -> bool {
self.words.len() == Self::num_words(self.domain())
&& self.wf_padding()
}
spec fn wf_padding(self) -> bool {
forall |idx: int, bit: usize|
0 <= idx < self.words.len() && bit < 64
&& self.domain() <= 64 * idx + bit
==> !#[trigger]
test_bit(self.words[idx], bit)
}
}abbrev Bitset.WF {d : Nat}
(words : Vector UInt64 (Bitset.numWords d)) :=
∀ (idx : Fin (Bitset.numWords d)) (bit : Fin 64),
d ≤ 64 * idx + bit →
words[idx].testBit (.ofNat bit) = false
structure Bitset (d : Nat) where
-- ...
wf : Bitset.WF wordsLean has the length invariant encoded already, so it only needs the
padding invariant. You can read WF as: “for all words and
for all bits, if the number corresponding to the word/bit is outside the
domain, then its bit should be 0” (represented as a helper function
testBit). We then attach WF to
Bitset by making it a field
wf : Bitset.WF words. Thus the data structure always
carries its proof of well-formedness.
Rust needs both invariants encoded in wf. The first one
is straightforward, that the number of words is correct. The
wf_padding invariant shows how Verus properties can be more
verbose than equivalent Lean properties in two ways:
Lean contains a rich library of auxiliary types to support
specification. To articulate “for all numbers less than 64”, you can
quantify over Fin 64, the type of such numbers. But in
Verus, you have to write
forall |bit: usize| bit < 64 ==> ....
Verus requires annotations to inform the underlying
SMT solver how to deal with quantifiers. The
#[trigger] annotation on test_bit tells the
solver how to instantiate idx and bit (see the Verus
guide).
In Verus, we can attach wf to Bitset in one
of two ways. One option is to add requires self.wf() and
ensures self.wf() on every method. The other option is to
use a specific mechanism called #[type_invariant].
I tried this, but it seems to interact poorly with methods requiring
longer-lived mutable borrows (such as union, which uses
iter_mut over words), so I abandoned it in favor of the
first approach.
The foundation of the bitset is checking whether it contains an
element. Given a number n, we look it up by first getting
its coordinates, or which word and which bit to check. Then we
test whether that word contains that bit.
impl Bitset {
#[vstd::contrib::auto_spec]
pub fn coords(n: usize) -> (usize, usize) {
(n / 64, n % 64)
}
pub fn contains(&self, n: usize) -> bool
requires self.wf(), n < self.domain()
{
let (idx, bit) = Self::coords(n);
test_bit(self.words[idx], bit)
}
}namespace Bitset
@[grind]
def coords (n : Fin d) : Fin (numWords d) × UInt64 :=
(⟨n / 64, by grind⟩, UInt64.ofNat (n % 64))
def contains (s : Bitset d) (n : Fin d) : Bool :=
let (idx, bit) := coords n
let word := s.words[idx]
word.testBit bitThe Rust code here is largely idiomatic with two Verus additions.
First, we would like to use functions such as coords and
num_words within both specifications (such as
wf) and implementations (such as contains). In
Verus, these are different languages, so auto_spec allows
coords to be used in both places. (This only works under
certain conditions, and I can’t find good documentation for
auto_spec, so hard to offer more details.) Second, in Rust,
contains has a requires clause indicating the
preconditions that the bitset is well-formed (recall the previous
section) and that n is within the domain.
The Lean code is simpler but with its own idiosyncrasies. The word
index produced by coords is of type
Fin (numWords d), which requires us to prove that
n / 64 < numWords d. Thankfully the grind
tactic can easily dispatch this proof. Note that the
@[grind] annotation on coords makes the
definition of coords transparent to the grind
tactic, similar to the concept of an broadcast proof in
Verus.
The two preconditions are already captured by the wf
field on Bitset and the type of n as
Fin d. Another notable detail is that in Lean, because
s.words is indexed by a Fin (i.e., a proof
that the index is in-bounds), indexing does not incur a bounds-check. In
Rust, while Verus does ensure that the bounds-check never panics, Verus
does not change the underlying Rust semantics. To actually eliminate the
runtime bounds-check, you have to write (provably safe)
unsafe code like this:
impl Bitset {
pub fn contains_fast(&self, n: usize) -> bool
requires self.wf(), n < self.domain()
{
let (idx, bit) = Self::coords(n);
let word = unsafe { self.words.get_unchecked(idx) };
test_bit(*word, bit)
}
}To prove the correctness of the bitset, we need to show that it behaves like a normal set. First, we need a way to convert a bitset into a normal set.
impl View for Bitset {
type V = Set<nat>;
closed spec fn view(&self) -> Set<nat> {
Set::range(0 as nat, self.domain as nat)
.filter(|n| {
let (idx, bit) = Self::coords(n as usize);
test_bit(self.words@[idx as int], bit)
})
}
}def toFinset (s : Bitset d) : Finset (Fin d) :=
Finset.univ.filter (s.contains ·)
@[simp]
theorem mem_toFinset {s : Bitset d} {n : Fin d} :
n ∈ s.toFinset ↔ s.contains n := by
simp [toFinset]Lean’s Mathlib provides a data structure of finite sets called Finset,
so we model the bitset as a Finset (Fin d), or a finite set
of the numbers up to d. We construct this with
Finset.univ (the set of all values in the type
Fin d), and filter it to those numbers contained in
s. Additionally, we provide a theorem which relates
Bitset.contains to the membership operator on
Finset and add it to the simp tactic
(comparable to grind, but with different search
strategies). This theorem is necessary to make the proofs of the
remaining theorems which connect Bitset to
Finset relatively compact.
(s.contains ·) instead
of just s.contains?
The eagle-eyed functional programmer may notice an unnecessary
eta-expansion where (s.contains ·) is shorthand for
fun x => s.contains x. We have to do this because
Finset.filter expects a function which returns a
Prop (a proposition, True or
False, potentially undecidable), but contains
returns a Bool (a boolean, true or
false, decidable). The eta-expansion allows Lean to
automatically convert from Bool to Prop on our
behalf. It’s useful to observe this distinction because it doesn’t exist
in Verus!
Verus provides a standard library of abstract collection
types for which the SMT solver provides a theory.
Thankfully this includes a set, so we model our bitset as a
Set<nat>. Verus provides first-class support for the
idea of “the abstract view on this concrete Rust object”, represented by
the View trait. Hence, we implement View for
Bitset with the view type being
Set<nat>.
In Verus, we define the set as a filtered range. The range goes from
0 to domain, and then we filter for containment. Note that
@ is a Verus shorthand for .view(). So
self.words@ converts the Rust type
Vec<u64> into the SMT/Verus type
Seq<u64>.
One small but annoying thing here is the difference in integer types.
Rust vectors are indexed by usize, while Verus sequences
are indexed by the abstract SMT int type,
hence we have to cast idx as int. A consequence of this
annoyance is that the implementation of contains is largely
duplicated here. Whereas in Lean we could directly use
contains at the specification and implementation levels, we
can’t do that in Verus. auto_spec does not work for
contains due to the index type mismatch.
Our bitset theorems will need to reason about a bunch of bit operations. These lower-level lemmas are more general than the bitset library, so we can extract them as standalone statements which might exist in a separate module. Here’s one example:
// bits.rs
pub broadcast proof fn lemma_test_bit_or(
a: u64, b: u64, bit: usize)
requires bit < 64
ensures #[trigger] test_bit(a | b, bit) == (
test_bit(a, bit) || test_bit(b, bit))
{
assert(test_bit(a | b, bit) == (
test_bit(a, bit) || test_bit(b, bit)))
by (bit_vector)
requires bit < 64;
}
// bitset.rs
broadcast use group_test_bit;namespace UInt64
@[simp, grind =]
theorem testBit_or (a b j : UInt64) :
(a ||| b).testBit j =
(a.testBit j || b.testBit j) := by
simp [testBit, bne]; bv_decideThis theorem states that bitwise-OR is equivalent to
logical-OR with respect to testBit. The
statement of the theorem is pretty similar between Verus and Lean. The
proof similarly mostly consists of “run a bitvector solver”, either
by (bit_vector) or bv_decide.
Annoyingly in Verus, you have to fully restate the theorem when stuffing
it into the solver. Both theorems are registered with solvers — Lean
using simp, grind like before, and Verus using broadcast.
The broadcast use declaration allows the bitset to
explicitly import these proofs into the solver’s scope.
Now we can put all the pieces together to define a verified method which constructs an empty bitset.
impl Bitset {
pub fn empty(d: usize) -> (set: Self)
ensures set.wf(),
set@ == Set::empty(),
set.domain() == d
{
let words = vec![0u64; Self::num_words(d)];
Bitset { domain: d, words }
}
}namespace Bitset
def empty (d : Nat) : Bitset d where
words := Vector.replicate (numWords d) 0
wf := by simp [WF, UInt64.testBit]
theorem toFinset_empty (d : Nat) :
(empty d).toFinset = ∅ := by
ext; simp [empty, contains, UInt64.testBit]In both Rust and Lean, we build a vector of length
num_words. We also ensure the resulting set is well-formed,
either by providing the proof wf := ... or by
ensures set.wf(). To declare that the resulting set is the
empty set, we assert that it is equal to the empty abstract set, either
Set::empty() in Verus or Finset.empty (∅) in
Lean.
Notably in Verus, we also declare that
set.domain() == d. This is because Verus only reasons
modularly about executable code such as empty, meaning
proofs about code using empty cannot look into its
implementation. This equality predicate is necessary for library clients
to write code such as Bitset::empty(10).contains(9), since
they need to know that d == 10 to know that 9
is within the domain. In Lean, the domain is already in the bitset’s
type, so this is not necessary.
Next, we see how to insert an element into the set. This follows a familiar pattern from the previous function, except now it involves mutation.
impl Bitset {
pub fn insert(&mut self, n: usize)
requires
self.wf(),
n < self.domain(),
ensures
final(self).wf(),
final(self).domain() == old(self).domain(),
final(self)@ == old(self)@.insert(n as nat)
{
let (idx, bit) = Self::coords(n);
self.words[idx] =
set_bit(self.words[idx], bit);
}
}def insert (s : Bitset d) (n : Fin d) : Bitset d :=
let (eq := _) (idx, bit) := coords n
let words := s.words.modify idx (·.setBit bit)
{ words, wf := by grind [s.wf] }
theorem toFinset_insert (s : Bitset d) (n : Fin d) :
(s.insert n).toFinset = insert n s.toFinset := by
ext; simp [contains, Bitset.insert]; grindThe Lean implementation uses a purely-functional style. (We’ll see an
imperative Lean style shortly.) Mutating the vector with
s.words.modify nominally produces a new vector, which we
put into a new Bitset. However, if no other code holds a
reference to words, then the Vector.modify
documentation says that the underlying storage is modified in-place. The
theorem that insert is correct is still short and sweet:
the insert on a Bitset behaves like insert on a
Finset.
One bizarre piece of Lean syntax is the (eq := _)
annotation on the first let-binding. This annotation is needed because
the wf proof is produced inside the definition of
insert rather than outside. Specifically, let-bindings with
pattern matching by default “forget” their provenance, so the
grind tactic does not know that
idx = (coords n).1. The (eq := _) annotation
puts that fact into the function’s type context, enabling
grind to succeed in proving well-formedness.
In Verus, we use an idiomatic &mut self reference.
This requires us to show that the data structure is still valid after
being changed, specifically we ensure final(self).wf() and
also ensure that domain has not changed. This uses the
old(..) and final(..) syntaxes to refer to a
variable’s value at the beginning and end of the function. The theorem
that insert is correct again looks like the one in Lean,
but using @ instead of toFinset.
Thus far the proofs have been relatively trivial — one or two tactics
in Lean, and fully automated in Verus. A more interesting example is
computing whether one bitset is the subset of another, relying on the
helper function word_subset(a, b) = a & !b == 0.
impl Bitset {
pub fn is_subset(&self, t: &Bitset)
-> (result: bool)
requires self.wf(), t.wf(),
self.domain() == t.domain()
ensures result == self@.subset_of(t@)
{
proof { self.lemma_is_subset(*t); }
self.words.iter().zip(&t.words).all(
|(a, b)| -> (r: bool)
ensures r == word_subset(*a, *b)
{ word_subset(*a, *b) })
}
proof fn lemma_is_subset(self, t: Bitset)
requires self.wf(), t.wf(),
self.domain() == t.domain()
ensures self@.subset_of(t@) <==>
forall |i: int| 0 <= i < self.words.len()
==> word_subset(#[trigger] self.words[i],
t.words[i])
{
if self@.subset_of(t@) {
assert forall |i: int, bit: usize|
0 <= i < self.words.len()
&& bit < 64
&& #[trigger] test_bit(self.words[i], bit)
implies test_bit(t.words[i], bit)
by { assert(self@.contains(
(64 * i + bit) as nat)); }
}
}
}def isSubset (s t : Bitset d) : Bool :=
s.words.isEqv t.words UInt64.wordSubset
theorem toFinset_isSubset (s t : Bitset d) :
s.isSubset t ↔ s.toFinset ⊆ t.toFinset := by
simp [isSubset,
Vector.isEqv_iff_rel, Finset.subset_iff,
UInt64.wordSubset_iff_testBit, contains]
refine ⟨by grind, fun h i hi j hj hb => ?_⟩
have := @h ⟨64 * i + j,
by grind [s.wf ⟨i, hi⟩ ⟨j, hj⟩]⟩
grindIn Rust, we idiomatically define is_subset using the
.iter().zip(..).all(..) iterator sequence. The semantics of
is_subset is modeled in terms of the abstract set
.subset_of method in Verus. However, Verus requires two
additional forms of specification. First, a postcondition on the
.all lambda states that it returns its body. This feels
unfortunately redundant, but Verus needs it due to its modularity
requirements. Second, Verus needs a lemma to support the
SMT solver, which cannot automatically verify
is_subset without it. The lemma itself relates the concepts
of subsetting and containment, saying that A ⊆ B iff all the words in A
are bit-subsets of the words in B.
In Lean, we use the Vector.isEqv
function which works similarly to .zip(..).all(..): it
returns true iff the two inputs are equivalent under the given function,
wordSubset. The correctness of isSubset is
similarly defined as iff A is a bit-subset of B, then
Finset of A is a subset of the Finset of B.
The proof involves several tactics, including helper theorems from the
Vector, Finset, and UInt64
modules.
Why these proofs? How did I know to define
lemma_is_subset exactly as it is, or to use
simp with its particular inputs? I did not know. I largely
relied on AI assistance (specifically Claude Fable 5.2) to
generate the proof terms and supporting lemmas. I’ll speak more to this
in the reflection at the end.
Finally, we conclude with the most ambitious method: unioning one
bitset into another. Specifically, union s t will add all
the elements from t to s, and it will return
true if s changed in the process. We will now
consider each language in turn.
In the Rust implementation, I picked a style I felt most idiomatic
for non-Verus Rust: using iter_mut().zip to get mutable
references to pairs of words, and then bitwise-OR-ing them
in a for-loop. In both the Rust and Lean versions, it would likely
simplify the proof to iterate over just an integer range, and then index
in the loop body. But my goal is to write implementations that look
beautiful, and then find the proofs that match.
impl Bitset {
pub fn union(&mut self, t: &Bitset) -> (changed: bool)
requires self.wf(), t.wf(), self.domain() == t.domain()
ensures final(self).wf(), final(self).domain() == old(self).domain(),
final(self)@ == old(self)@.union(t@),
changed == !(final(self)@ =~= old(self)@)
{
let ghost old_words = old(self).words@;
let ghost new_words = final(self).words@;
proof { t.lemma_is_subset(*self); }
let mut changed = false;
#[verifier::loop_isolation(false)]
for (s_word, t_word) in iter: self.words.iter_mut().zip(&t.words)
invariant forall |i: int| 0 <= i < iter.index() ==>
#[trigger] new_words[i] == old_words[i] | t.words[i],
changed == !forall |i: int| 0 <= i < iter.index() ==>
word_subset(#[trigger] t.words[i], old_words[i]),
{
let orig_word = *s_word;
*s_word |= *t_word;
changed |= *s_word != orig_word;
}
changed
}
}The majority of the function is dedicated to Verus code. The pre/post
conditions are similar to those for insert. The loop
performs the bitwise-OR over all the words of
self, and updates changed accordingly. This
loop requires an invariant to describe its behavior. The first invariant
says “the function has mutated self for all i
up to the current iteration”, and the second invariant says “changed
reflects whether t is not a subset of self”.
The loop_isolation(false) attribute allows the solver to
reason about the loop in its context, so for example we do not need to
write final(self).wf() as part of the invariant.
changed use
=~= instead of ==?
Verus uses a =~= b to mean “a is
extensionally equal to b”. This is primarily used for data
structures, so for a set this means k ∈ a ⇔ k ∈ b. Normally
Verus automatically converts == to =~= when
equating sets, but this conversion only happens for simple clauses.
Because of the negation operator, we have to spell out
=~=.
One confusing element is that the loop invariant has to be written in
terms of the “ghost” variables (non-runtime variables)
old_words and new_words rather than
self.words@ and final(self).words@ directly.
If you substitute the let ghost definitions into the
invariant, then Rust will complain that
self.words.iter_mut() conflicts with
final(self). Intuitively this does not make sense, because
let ghost should disappear at runtime, but it seems a
limitation of Verus’s particular macro expansion.
Finally, observe that the lemma_is_subset must be
imported into the solver’s context via the proof { .. }
block for the whole proof to succeed.
Union can be implemented in several ways depending on the style of programming and constraints in terms of computation and memory.
A straightforward functional-style implementation of
union in Lean which uses Lean’s libraries looks like
this:
def unionFunc (s t : Bitset d) : Bitset d × Bool :=
let Δ := !t.isSubset s
let words := s.words.mapFinIdx fun i word _ => word ||| t.words[i]
({ words, wf := by grind [s.wf, t.wf] }, Δ)This uses Vector.mapFinIdx
to map over each word along with its index, bitwise-ORing
with t. The proof of well-formedness is straightforward.
However, the Δ implementation is less efficient than in
Rust, because (a) isSubset requires three bit operations
per word rather than one, and (b) isSubset requires a
second pass over the data with all its attendant cache issues.
This simple implementation has a correspondingly simple proof of correctness:
theorem toFinset_unionFunc_words (s t : Bitset d) :
let (s', _) := s.unionFunc t
s'.toFinset = s.toFinset ∪ t.toFinset := by
ext; simp [contains]
theorem toFinset_unionFunc_Δ (s t : Bitset d) :
let (s', Δ) := s.unionFunc t
Δ ↔ s'.toFinset ≠ s.toFinset := by
have := toFinset_unionFunc_words s t
simp_all [unionFunc, ← toFinset_isSubset]The first theorem says that unionFunc on bitsets
implements union on Finset. The second theorem says that
iff Δ is true, then the unioned set is not equal to the
original set.
Another possibility is to write an imperative-style implementation using Lean’s support for monads:
def unionImpWords {n} (s t : Vector UInt64 n) : Vector UInt64 n × Bool := Id.run do
let mut s' := s
let mut Δ := false
for h : i in [0 : n], tw in t do
let sw := s'[i]
let sw' := sw ||| tw
Δ := Δ || sw' != sw
s' := s'.set i sw'
return (s', Δ)
def unionImp (s t : Bitset d) : Bitset d × Bool :=
let (eq := _) (sw', Δ) := unionImpWords s.words t.words
let s' := { words := sw', wf := by grind [unionImpWords_spec, s.wf, t.wf] }
(s', Δ)This code reads more like the Rust implementation. However, the inner
loop needs to be factored into a separate unionImpWords
helper function. The reason is that unlike empty and
insert, here the proof of well-formedness
(wf := by ...) requires nontrivial reasoning. The proof is
therefore dramatically simpler if we can write a lemma about
unionImpWords and use that inside the proof of
well-formedness as well as in the proof of functional correctness of
union. This pattern is often used in Lean libraries by
having an inner “raw” data structure which lacks an invariant (e.g., Std.DHashMap.Raw),
and then an outer “nice” data structure which bundles the raw data with
an invariant (e.g., Std.DHashMap).
I originally implemented unionImpWords with a subtle
performance issue. If the for-loop iterates over both vectors like
sw in s, tw in t, then both s' and the
for-loop’s iterator hold a reference to the same input data, which
causes a copy rather than in-place update when s'.set is
called.
The proof of correctness for unionImpWords involves
using Lean’s vcgen
tactic for verifying imperative code:
open Std.WP in
set_option experimental.vcgen true in
theorem unionImpWords_spec {n} (s t : Vector UInt64 n) :
let (s', Δ) := unionImpWords s t
(∀ j : Fin n, s'[j] = s[j] ||| t[j])
∧ Δ = !t.isEqv s UInt64.wordSubset := by
generalize h : unionImpWords s t = r
apply Id.of_run_eq_wp h
simp only [Std.toStream, Std.Stream.next?, Std.Rii.Sliceable.mkSlice]
vcgen invariants
· fun pref _ (ws, Δ, sub) =>
(∀ j (_ : j < n), ws[j] = if j < pref.length then s[j] ||| t[j] else s[j])
∧ (Δ ↔ ∃ j, ∃ (_ : j < n), j < pref.length ∧ !(t[j].wordSubset s[j]))
∧ Subarray.array sub = t.toArray
∧ Subarray.start sub = pref.length
∧ Subarray.stop sub = n
with finish [Subarray.array, Subarray.start, Subarray.stop, Vector.isEqv_iff_rel]This proof is tough to explain without a lot more context — I
recommend reading Lean’s guide to
vcgen. Focus on the theorem statement which describes
the high-level behavior of unionImpWords. First, the
resulting words contain the bitwise-OR of the input words.
Second, the Δ boolean reflects whether the second set of
words is not a subset of the first set (duplicating the implementation
of isSubset, which could be factored into a helper).
The unionImpWords_spec theorem is used in the
unionImp well-formedness proof, and it also supports the
corresponding toFinset_unionImp_words and
toFinset_unionImp_Δ theorems which are very similar to
those for unionFunc, so I do not reproduce them here.
An intermediate approach is to write in a functional-inductive style. This loses some of the conciseness of the functional-library style, but it has equivalent efficiency to the imperative style while requiring a much smaller proof:
def unionInd (s t : Bitset d) : Bitset d × Bool :=
go s 0 false
where
go (s : Bitset d) (i : Nat) (Δ : Bool) : Bitset d × Bool :=
if _ : i < numWords d then
let sw := s.words[i]
let sw' := sw ||| t.words[i]
let s := {
words := s.words.set i sw',
wf := by grind [s.wf, t.wf]
}
go s (i + 1) (Δ || sw != sw')
else (s, Δ)
theorem unionInd.go_spec (t s : Bitset d) (i : Nat) (Δ : Bool) :
let (s', Δ') := go t s i Δ
(∀ j : Fin (numWords d),
s'.words[j] = if i ≤ j then s.words[j] ||| t.words[j] else s.words[j])
∧ (Δ' ↔ Δ ∨
∃ j : Fin (numWords d), i ≤ j ∧ !(t.words[j].wordSubset s.words[j])) := by
simp only [Fin.forall_iff, Fin.exists_iff]
fun_induction go t s i Δ <;> grindLike the imperative proof, this requires a separate
unionInd.go_spec theorem which proves a lower-level
statement of behavior about unionInd through induction.
Specifically, it proves that unionInd implements
union for indices starting at i and
onward.
Note that the if-expression requires the syntax
_ : i < numWords d for a similar reason to the
let (eq := _) annotation earlier. It introduces the fact
that i < numWords d into the function body’s type
context, which allows the indexing such as s.words[i] to
prove that i is in-bounds.
Overall, I am fairly pleased with the result in both languages. I felt that I did not have to seriously sacrifice code style or performance to achieve correctness.
I did experience several “abstraction taxes” where trying to write a clean implementation led to an ugly or impossible proof.
Lean: I disliked how I have to sprinkle various
let (eq := _) and if _ : ... annotations
around to bring a proof term into the function body scope. In the
union example, I had to forgo abstraction to achieve
optimal performance.
Verus: The spec language being different from
the implementation language introduces a lot of papercuts, like the
limitations of #[auto_spec]. I also had to fight a bit to
use the abstractions I wanted like .iter().zip(..).all(..),
which required an additional lemma specifically to model the interaction
of zip, all, and the postcondition. It wasn’t
impossible, but the solver would have been happier if I wrote C-like
Rust.
I found that my AI assistant would continually make lots of small choices that passed the verifier but reduced the code quality (often related to the abstraction tax). For example in Verus, the AI will happily inline definitions into lemmas (causing repeated code), and it will stuff a function full of proofs even when some of those facts ought to live as standalone statements. Taste still matters!
I came into this experience with a lot of skepticism about primarily SMT-based approaches to verification. I still have no idea how people are supposed to debug the spartan “postcondition not satisfied” errors that get emitted from Verus, versus interactively proving theorems in Lean and always having a clear statement of the current goal and its environment. But perhaps proof is a non-issue now due to AI. I certainly would have taken 10x longer to write both the Verus and Lean proofs if purely by hand.
At least, specifications will always matter because they need to be
either written or reviewed by humans. Lean has an unambiguously better
spec language than Verus, both for its consistency (same as
implementation language) and for its breadth (full of rich primitives
like Fin and Finset). Lean offers the ability
to express both extrinsic and intrinsic forms of verification, while
Verus seems largely targeted at extrinsic verification. Yet, Lean as an
implementation language is still much more experimental compared to the
battle-tested Rust language and compiler. My intuition is that Verus
feels like the near future of proof-oriented programming, and Lean feels
like the far future.