文章标题:Verus 与 Lean 中的面向证明编程
正文: 现在有很多人对软件验证感兴趣,一方面是因为 AI 正在发现许多 bug,另一方面是因为 AI 正在降低形式化方法的入门门槛。我相信验证的未来是面向证明编程(proof-oriented programming),这个术语我取自 F*。面向证明编程的一个核心要素是:系统的规约可以直接针对其实现进行证明。截至 2026 年 11 月,有两种面向证明编程语言似乎有望流行起来:Verus 和 Lean。本文描述了一个小型案例研究,用以说明这两种方法之间的对比。
验证工具的一个常见问题是,它们可以验证你系统的模型,但无法验证系统本身。例如,人们可以在 TLA+ 中为 Raft 这样的共识协议建模其正确性,但 TLA+ 无法检查 Raft 的 Rust 实现是否编写正确。有很多变通方法,比如差分测试,但希望未来不会仅仅由变通方法构成。
具体来说,我们将实现一个经过验证的 bitset。bitset 是一种用于小固定域上数字集合的高效数据结构。例如,假设我们想要一个可以包含数字 0 到 127 的集合。我们可以将该集合表示为两个 64 位整数。要插入数字 5,我们将第一个整数上的第 5 位设为 1。像集合并集这样的操作可以归约为按位或这样的位运算。
Bitset 是一个很好的案例研究,因为它们的实现很小且自包含,而且它们的规约很直接:bitset 应该表现得像一个“普通”或“抽象”集合。此外,Verus 和 Lean 似乎都没有 bitset 实现,所以这对我来说是一次有趣的练习!作为背景,我对 Rust 了解很多,对 Lean 了解中等,对 Verus 了解很少。我提前为错误或不必要的复杂证明道歉。本文中的所有代码都公开在 willcrichton/verified-bitset。
AI 披露:本文的文字完全是手工撰写的。我主要在轻度 AI 辅助下手动编写了规约。我大量使用 AI 来生成证明项。
Bitset 定义
bitset 由一个域(domain)定义,即集合中元素的最大数量。bitset 包含一个固定大小整数的数组,为简单起见始终是 64 位。这个数组需要 ⌈domain / 64⌉ 个字。我们将看左侧的 Verus 定义,以及右侧的 Lean 定义(在移动端则是上方 / 下方)。
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)
-- ...
一个区别是,域在 Rust 中编码为一个字段,而在 Lean 中编码为类型参数。类型参数编码似乎是最面向证明的设计,因为字段 words 在其类型中携带其长度 numWords d(即它是内在验证的)。但字段编码对 Rust 来说是惯用的,而类型参数不会按预期工作——像 [u64; num_words(d)] 这样的类型目前在 Rust 中不稳定,并且在 Verus 中不受支持(因此我们必须使用外在验证)。
另一个区别是,Rust 的 words 数组包含未装箱的整数,而在 Lean 中,words 会分别装箱每个字。我们需要在 Lean 中使用一种专门的未装箱整数数组类型,才能与 Rust 在内存上对等。
Rust 中的 num_words 实现比 Lean 更复杂,原因有两点。第一是 auto_spec,我们稍后会讨论。第二是天花板除法的特殊实现方式。在 Rust 中,定义域是 usize,意味着它可能溢出(Verus 会严格防止这种情况)。表达式 (d + 63) / 64 在 d > usize::MAX - 63 时会溢出。这在 Lean 中不是问题,因为大多数算术运算发生在自然数(Nat)上,而自然数的大小是无界的。
经验丰富的 Rust 程序员可能会注意到 div_ceil 正是我们想要的函数。问题在于,截至撰写本文时,Verus 标准库并未为 div_ceil 提供形式化语义。理论上我们可以自己提供一个,但我不想让这篇文章比它本身已经更复杂了!
最后一个区别是我们如何编码数据结构不变式。Bitset 有两个关键不变式:
- 数组应当有足够的 word 来容纳整个定义域。
- 最后一个 word 末尾未使用的“填充”位应当为零。(这将是证明我们的 is_subset 方法正确性所需要的。)
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 words
Lean 已经编码了长度不变式,因此它只需要填充不变式。你可以把 WF 读作:“对于所有 word 和所有 bit,如果该 word/bit 对应的数字在定义域之外,那么它的 bit 应当为 0”(由一个辅助函数 testBit 表示)。然后我们通过将 WF 作为字段 wf : Bitset.WF words 附加到 Bitset 上。因此,该数据结构始终携带其良构性证明。
Rust 需要在 wf 中编码两个不变式。第一个很直接,即 word 的数量是正确的。wf_padding 不变式展示了 Verus 属性在两个方面可能比等价的 Lean 属性更冗长:
- Lean 包含一个丰富的辅助类型库来支持规约。要表达“对于所有小于 64 的数字”,你可以对 Fin 64(这类数字的类型)进行量化。但在 Verus 中,你必须写 forall |bit: usize| bit < 64 ==> ...。
- Verus 需要注解来告知底层 SMT 求解器如何处理量词。test_bit 上的 #[trigger] 注解告诉求解器如何实例化 idx 和 bit(参见 Verus 指南)。
在 Verus 中,我们可以通过两种方式之一将 wf 附加到 Bitset 上。一种选择是在每个方法上添加 requires self.wf() 和 ensures self.wf()。另一种选择是使用一种称为 #[type_invariant] 的特定机制。我尝试过这种方法,但它似乎与需要更长生命周期可变借用的方法(例如 union,它对 words 使用 iter_mut)交互不佳,因此我放弃了它,转而采用第一种方法。
Bitset 包含关系
Bitset 的基础是检查它是否包含某个元素。给定一个数字 n,我们通过首先获取它的坐标,即要检查哪个 word 和哪个 bit,来查找它。然后我们测试该 word 是否包含该 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 bit
这里的 Rust 代码基本是惯用写法,只加了两处 Verus 扩展。首先,我们希望能在规格(如 wf)和实现(如 contains)中同时使用 coords 和 num_words 这类函数。在 Verus 中,规格与实现属于不同的语言,因此 auto_spec 允许 coords 在两处都能使用。(这仅在特定条件下有效,而且我找不到关于 auto_spec 的完善文档,所以难以提供更多细节。)其次,在 Rust 中,contains 带有一个 requires 子句,用以说明前置条件:bitset 是良构的(回顾上一节),并且 n 位于定义域之内。
Lean 代码更简单,但有其自身的独特之处。coords 生成的 word 索引类型为 Fin (numWords d),这要求我们证明 n / 64 < numWords d。所幸 grind 策略可以轻松完成这一证明。注意,coords 上的 @[grind] 注解使 coords 的定义对 grind 策略透明,这类似于 Verus 中 broadcast proof 的概念。
这两个前置条件已经由 Bitset 上的 wf 字段以及 n 的类型 Fin d 所涵盖。另一个值得注意的细节是,在 Lean 中,由于 s.words 以 Fin 为索引(即索引在界内的证明),索引操作不会产生边界检查。在 Rust 中,虽然 Verus 确保边界检查永不 panic,但 Verus 并不改变底层 Rust 语义。要真正消除运行时边界检查,你必须编写(可证明安全的)unsafe 代码,如下所示:
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)
}
}
Bitset 模型
为了证明 bitset 的正确性,我们需要证明它的行为与普通集合一致。首先,我们需要一种将 bitset 转换为普通集合的方法。
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 的 Mathlib 提供了一种名为 Finset 的有限集数据结构,因此我们将 bitset 建模为 Finset (Fin d),即不超过 d 的数字构成的有限集。我们用 Finset.univ(类型 Fin d 中所有值的集合)构造它,并过滤出 s 中包含的那些数字。此外,我们提供了一个定理,将 Bitset.contains 与 Finset 上的成员运算符关联起来,并将其加入 simp 策略(与 grind 类似,但搜索策略不同)。这个定理是必要的,它使得其余将 Bitset 与 Finset 关联起来的定理的证明相对紧凑。
眼尖的函数式程序员可能会注意到一处不必要的 eta 展开,其中 (s.contains ·) 是 fun x => s.contains x 的简写。我们必须这样做,因为 Finset.filter 期望一个返回 Prop(命题,True 或 False,可能不可判定)的函数,而 contains 返回的是 Bool(布尔值,true 或 false,可判定)。eta 展开让 Lean 能够自动替我们从 Bool 转换为 Prop。观察这一区别很有用,因为它在 Verus 中并不存在!
Verus 提供了一个抽象集合类型的标准库,SMT 求解器为其提供了理论支持。所幸其中包含集合,因此我们将 bitset 建模为 Set<nat>。Verus 对“这个具体 Rust 对象上的抽象视图”这一概念提供了一等支持,由 View trait 表示。因此,我们为 Bitset 实现 View,视图类型为 Set<nat>。
文章标题:Verus 与 Lean 中的面向证明编程
正文: 在 Verus 中,我们将集合定义为一个经过过滤的范围。该范围从 0 到 domain,然后我们过滤出包含关系。注意 @ 是 Verus 中 .view() 的简写。因此 self.words@ 将 Rust 类型 Vec<u64> 转换为 SMT/Verus 类型 Seq<u64>。
这里一个虽小但恼人的问题是整数类型的差异。Rust 向量以 usize 为索引,而 Verus 序列以抽象的 SMT int 类型为索引,因此我们必须将 idx 转换为 int。这种恼人之处的一个后果是,contains 的实现在这里很大程度上是重复的。而在 Lean 中,我们可以在规范和实现层面直接使用 contains,在 Verus 中却做不到。由于索引类型不匹配,auto_spec 对 contains 不起作用。
位推理引理
我们的位集定理需要推理一系列位操作。这些底层引理比位集库更为通用,因此我们可以将它们提取为独立的陈述,它们可能存在于单独的模块中。下面是一个例子:
// 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_decide
该定理陈述的是:就 testBit 而言,按位或等价于逻辑或。该定理的陈述在 Verus 和 Lean 之间非常相似。证明同样主要由“运行一个位向量求解器”构成,要么通过 (bit_vector),要么通过 bv_decide。恼人的是,在 Verus 中,把它塞进求解器时你必须完整地重述该定理。两个定理都注册到了求解器——Lean 像之前一样使用 simp、grind,Verus 则使用 broadcast。broadcast use 声明允许位集将这些证明显式导入求解器的作用域。
一个空位集
现在我们可以把所有部分组合起来,定义一个经过验证的方法来构造一个空位集。
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]
在 Rust 和 Lean 中,我们都构建一个长度为 num_words 的向量。我们还确保结果集合是良构的,要么通过提供证明 wf := ...,要么通过 ensures set.wf()。为了声明结果集合是空集,我们断言它等于空抽象集,在 Verus 中是 Set::empty(),在 Lean 中是 Finset.empty(∅)。
值得注意的是,在 Verus 中我们还声明了 set.domain() == d。这是因为 Verus 只对 empty 这类可执行代码进行模块化推理,这意味着使用 empty 的代码的证明无法查看其实现。这个相等谓词对于库客户端编写诸如 Bitset::empty(10).contains(9) 这样的代码是必要的,因为他们需要知道 d == 10 才能知道 9 在域内。在 Lean 中,域已经存在于位集的类型中,因此这并不必要。
集合插入
接下来,我们看看如何向集合中插入一个元素。这沿用了前一个函数中熟悉的模式,只是现在涉及可变性。
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]; grind
Lean 实现采用纯函数式风格。(我们稍后会看到一种命令式的 Lean 风格。)用 s.words.modify 修改向量名义上会产生一个新向量,我们把它放进一个新的 Bitset 中。然而,如果没有其他代码持有对 words 的引用,那么 Vector.modify 的文档说明底层存储是原地修改的。insert 正确性的定理依然简短而优雅:对 Bitset 的 insert 行为等同于对 Finset 的 insert。
Lean 语法中一个奇怪的地方是第一个 let 绑定上的 (eq := _) 注解。之所以需要这个注解,是因为 wf 证明是在 insert 的定义内部而非外部产生的。具体来说,带模式匹配的 let 绑定默认会“遗忘”其来源,因此 grind 策略不知道 idx = (coords n).1。 (eq := _) 注解把这个事实放入函数的类型上下文中,使 grind 能够成功证明良构性。
在 Verus 中,我们使用惯用的 &mut self 引用。这要求我们证明数据结构在修改后仍然有效,具体来说我们确保 final(self).wf(),并且确保 domain 没有改变。这里使用了 old(..) 和 final(..) 语法来引用变量在函数开头和结尾的值。insert 正确性的定理同样看起来与 Lean 中的类似,但使用 @ 而非 toFinset。
子集判定
到目前为止,这些证明都相对简单——在 Lean 中只需一两个策略,在 Verus 中则完全自动化。一个更有趣的例子是计算一个 bitset 是否是另一个的子集,这依赖于辅助函数 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 == [email protected]_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 [email protected]_of(t@) <==>
forall |i: int| 0 <= i < self.words.len()
==> word_subset(#[trigger] self.words[i],
t.words[i])
{
if [email protected]_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([email protected](
(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⟩]⟩
grind
文章标题:Proof-Oriented Programming in Verus vs. Lean
正文: 在 Rust 中,我们惯用地通过 .iter().zip(..).all(..) 迭代器序列来定义 is_subset。is_subset 的语义在 Verus 中是以抽象集合的 .subset_of 方法为模型来描述的。然而,Verus 需要额外两种形式的规约。首先,.all lambda 上的后置条件声明它返回其函数体。这虽然显得冗余,但 Verus 因其模块化要求而需要它。其次,Verus 需要一个引理来辅助 SMT 求解器,没有它就无法自动验证 is_subset。该引理本身将子集与包含这两个概念联系起来,即 A ⊆ B 当且仅当 A 中的所有字都是 B 中字的位子集。
在 Lean 中,我们使用 Vector.isEqv 函数,其工作方式与 .zip(..).all(..) 类似:当且仅当两个输入在给定函数 wordSubset 下等价时,它返回 true。isSubset 的正确性同样定义为:当且仅当 A 是 B 的位子集时,A 的 Finset 是 B 的 Finset 的子集。证明涉及若干 tactic,包括来自 Vector、Finset 和 UInt64 模块的辅助定理。
为什么需要这些证明?我怎么知道要恰好这样定义 lemma_is_subset,或者要用带有特定输入的 simp?我并不知道。我在很大程度上依赖 AI 辅助(具体来说是 Claude Fable 5.2)来生成证明项和支持引理。我会在最后的反思中进一步讨论这一点。
集合并集
最后,我们以最具雄心的一个方法作结:将一个位集并入另一个位集。具体来说,union s t 会把 t 中的所有元素添加到 s 中,如果 s 在此过程中发生了变化则返回 true。我们现在依次考察每种语言。
Verus 中的并集
在 Rust 实现中,我选择了一种我认为对非 Verus Rust 最惯用的风格:使用 iter_mut().zip 获取字对的可变引用,然后在 for 循环中对它们按位或。在 Rust 和 Lean 两个版本中,只遍历一个整数范围然后在循环体内索引,很可能会简化证明。但我的目标是写出看起来漂亮的实现,然后再找到与之匹配的证明。
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
}
}
该函数的大部分内容都用于 Verus 代码。前置/后置条件与 insert 的类似。循环对 self 的所有字执行按位或,并相应地更新 changed。该循环需要一个不变式来描述其行为。第一个不变式表示“该函数已对截至当前迭代的所有 i 修改了 self”,第二个不变式表示“changed 反映了 t 是否为 self 的子集”。loop_isolation(false) 属性允许求解器在其上下文中对循环进行推理,因此例如我们不需要把 final(self).wf() 写进不变式。
Verus 用 a =~= b 表示“a 与 b 外延相等”。这主要用于数据结构,因此对于集合而言,它表示 k ∈ a ⇔ k ∈ b。通常 Verus 在比较集合时会自动把 == 转换为 =~=,但这种转换只发生在简单子句中。由于取反运算符的存在,我们必须显式写出 =~=。
一个令人困惑的地方是,循环不变式必须用“幽灵”变量(非运行时变量)old_words 和 new_words 来写,而不能直接用 self.words@ 和 final(self).words@。如果把 let ghost 定义代入不变式,Rust 就会报错说 self.words.iter_mut() 与 final(self) 冲突。直觉上这说不通,因为 let ghost 在运行时本应消失,但这似乎是 Verus 特定宏展开的一个限制。
最后要注意,lemma_is_subset 必须通过 proof { .. } 块导入到求解器的上下文中,整个证明才能成功。
Lean 中的并集
并集可以有多种实现方式,取决于编程风格以及在计算和内存方面的约束。
函数式并集,库驱动
在 Lean 中一个直接使用 Lean 库的函数式风格并集实现如下所示:
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] }, Δ)
这里使用 Vector.mapFinIdx 对每个 word 及其索引进行映射,与 t 做按位或。良构性证明很直接。然而,Δ 的实现比 Rust 中效率低,因为 (a) isSubset 每个 word 需要三次位运算而不是一次,(b) isSubset 需要对数据做第二遍遍历,并伴随所有相关的缓存问题。
这个简单实现有着相应简单的正确性证明:
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]
第一个定理说明 bitset 上的 unionFunc 实现了 Finset 上的并集。第二个定理说明当且仅当 Δ 为真时,并集后的集合不等于原集合。
命令式并集
另一种可能是使用 Lean 对 monad 的支持编写命令式风格的实现:
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', Δ)
这段代码读起来更像 Rust 实现。然而,内层循环需要抽取到一个单独的 unionImpWords 辅助函数中。原因在于,与 empty 和 insert 不同,这里的良构性证明(wf := by ...)需要非平凡的推理。因此,如果我们能写一个关于 unionImpWords 的引理,并在良构性证明以及并集函数正确性证明中使用它,证明就会大大简化。这种模式在 Lean 库中经常使用:内层是一个缺少不变式的“原始”数据结构(例如 Std.DHashMap.Raw),外层是一个把原始数据与不变式捆绑在一起的“友好”数据结构(例如 Std.DHashMap)。
文章标题:Proof-Oriented Programming in Verus vs. Lean
正文: 我最初实现的 unionImpWords 存在一个微妙的性能问题。如果 for 循环像 sw in s, tw in t 这样同时遍历两个向量,那么 s' 和 for 循环的迭代器都会持有对同一输入数据的引用,这会导致在调用 s'.set 时发生复制,而不是原地更新。
unionImpWords 的正确性证明涉及使用 Lean 的 vcgen 策略来验证命令式代码:
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]
如果没有更多的上下文,这个证明很难解释——我建议阅读 Lean 的 vcgen 指南。请关注定理陈述,它描述了 unionImpWords 的高层行为。首先,结果字包含输入字的按位或。其次,Δ 布尔值反映第二组字是否不是第一组字的子集(重复了 isSubset 的实现,本可以提取到一个辅助函数中)。
unionImpWords_spec 定理用于 unionImp 的良构性证明,并且它还支持相应的 toFinset_unionImp_words 和 toFinset_unionImp_Δ 定理,这些定理与 unionFunc 的定理非常相似,因此我在此不再赘述。
函数式 union,归纳式
一种中间方法是使用函数式-归纳式风格来编写。这失去了一些函数式库风格的简洁性,但它具有与命令式风格等效的效率,同时需要的证明要小得多:
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 Δ <;> grind
与命令式证明一样,这需要一个单独的 unionInd.go_spec 定理,它通过归纳法证明关于 unionInd 的低层行为陈述。具体来说,它证明 unionInd 对从 i 开始的索引及之后实现了 union。
注意,if 表达式需要 _ : i < numWords d 语法,原因与之前的 let (eq := _) 注解类似。它将 i < numWords d 这一事实引入函数体的类型上下文中,这使得像 s.words[i] 这样的索引操作能够证明 i 在边界内。
反思
总体而言,我对两种语言的结果都相当满意。我觉得我并没有为了达到正确性而严重牺牲代码风格或性能。
我确实经历了几次“抽象税”,即试图编写干净的实现却导致了丑陋或不可能的证明。
- Lean:我不喜欢必须到处散布各种 let (eq := _) 和 if _ : ... 注解,以将证明项引入函数体作用域。在 union 示例中,我不得不放弃抽象以实现最优性能。
文章标题:Proof-Oriented Programming in Verus vs. Lean
- Verus:规约语言与实现语言不同,带来了很多小麻烦,比如
#[auto_spec]的限制。我还得费一番功夫才能用上我想要的抽象,比如.iter().zip(..).all(..),这需要额外一条引理来专门刻画 zip、all 和后置条件之间的交互。这并非做不到,但如果我写成 C 风格的 Rust,求解器会高兴得多。
我发现我的 AI 助手会不断做出大量小选择,这些选择能通过验证器,却降低了代码质量(往往与抽象税有关)。例如在 Verus 中,AI 会毫不犹豫地把定义内联进引理(导致代码重复),还会把函数塞满证明,即使其中某些事实本应作为独立陈述存在。品味仍然很重要!
我带着对以 SMT 为主的验证方法的诸多怀疑进入这次体验。我仍然不知道人们该如何调试 Verus 发出的那种简陋的“后置条件未满足”错误,相比之下在 Lean 中交互式证明定理时,总能清楚地看到当前目标及其环境。但也许有了 AI,证明现在已不是问题。如果纯靠手工,我写 Verus 和 Lean 证明肯定都要多花 10 倍时间。
至少,规约始终重要,因为它们需要由人来编写或审阅。Lean 的规约语言无疑比 Verus 更好,既因为其一致性(与实现语言相同),也因为其广度(充满 Fin 和 Finset 这类丰富的原语)。Lean 能够表达外在验证和内在验证两种形式,而 Verus 似乎主要面向外在验证。然而,作为实现语言,Lean 相比久经考验的 Rust 语言和编译器仍处于实验阶段得多。我的直觉是:Verus 像是面向证明的编程的近未来,而 Lean 像是远未来。