Verif_hashhash.c 的正确性证明

本章证明 C 程序 hash.c 正确实现了 hashfun.v 中的函数模型。 hashfun.v 那边证的是「函数模型作为 字符串键的键值映射行为正确」。 两份证明合起来,就得到 hash.c 的正确行为。

通常的样板

Require VC.Preface. (* 检查 VST 的正确版本 *)
Require Import VST.floyd.proofauto.
Require Import VST.floyd.library.
Require Import VC.hash.
#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.
Require Import VC.hints. (* 为本教程导入特殊提示。 *)
现在导入几个 VST 库; 它们不在 VST.floyd.proofauto 的标准导入里。
Require Import VST.msl.wand_frame.
Require Import VST.msl.iter_sepcon.
Require Import VST.floyd.reassoc_seq.
Require Import VST.floyd.field_at_wand.
现在我们导入函数模型。
Require Import VC.Hashfun.

函数规约

从 C 字符串库导入(见 Verif_strlib)

Definition strcmp_spec :=
 DECLARE _strcmp
  WITH str1 : val, s1 : list byte, str2 : val, s2 : list byte
  PRE [ tptr tschar, tptr tschar ]
    PROP ()
    PARAMS (str1; str2)
    SEP (cstring Ews s1 str1; cstring Ews s2 str2)
  POST [ tint ]
   EX i : int,
    PROP (if Int.eq_dec i Int.zero then s1 = s2 else s1 ≠ s2)
    RETURN (Vint i)
    SEP (cstring Ews s1 str1; cstring Ews s2 str2).

Definition strcpy_spec :=
 DECLARE _strcpy
  WITH dest : val, n : Z, src : val, s : list byte
  PRE [ tptr tschar, tptr tschar ]
    PROP (Zlength s < n)
    PARAMS (dest; src)
    SEP (data_at_ Ews (tarray tschar n) dest; cstring Ews s src)
  POST [ tptr tschar ]
    PROP ()
    RETURN (dest)
    SEP (cstringn Ews s n dest; cstring Ews s src).

Definition strlen_spec :=
 DECLARE _strlen
  WITH s : list byte, str: val
  PRE [ tptr tschar ]
    PROP ( )
    PARAMS (str)
    SEP (cstring Ews s str)
  POST [ size_t ]
    PROP ()
    RETURN (Vptrofs (Ptrofs.repr (Zlength s)))
    SEP (cstring Ews s str).

字符串函数:复制、散列

Definition copy_string_spec : ident × funspec :=
 DECLARE _copy_string
 WITH s: val, sigma : list byte, gv: globals
 PRE [ tptr tschar ]
    PROP ()
    PARAMS (s) GLOBALS(gv)
    SEP (cstring Ews sigma s; mem_mgr gv)
 POST [ tptr tschar ]
    EX p: val,
      PROP ( ) RETURN (p)
      SEP (cstring Ews sigma s;
           cstring Ews sigma p;
           malloc_token Ews (tarray tschar (Zlength sigma + 1)) p;
           mem_mgr gv).

Definition hash_spec : ident × funspec :=
  DECLARE _hash
  WITH s: val, contents : list byte
  PRE [ tptr tschar ]
          PROP ()
          PARAMS (s)
          SEP (cstring Ews contents s)
  POST [ tuint ]
        PROP ()
        RETURN (Vint (Int.repr (hashfun contents)))
        SEP (cstring Ews contents s).

哈希表的数据结构

下面几个是常用的 C 结构体类型缩写
Definition tcell := Tstruct _cell noattr.
Definition thashtable := Tstruct _hashtable noattr.
一个 list_cell 分四部分:
  • 一个链表 cons 单元,含键指针 kp、整数 count, 以及指向下一个链表元素的指针 next;
  • 键指针指向键字符串 (空字符结尾的 char 数组);
  • 这个 cons 单元由 malloc 取得, 必须能被 free 释放, 所以配一个 malloc_token 作为凭证;
  • 键字符串同样配一个 malloc_token,以便释放
Definition list_cell (key: list byte) (count: Z) (next: val) (p: val): mpred :=
 EX kp: val, cstring Ews key kp
             × malloc_token Ews (tarray tschar (Zlength key + 1)) kp
             × data_at Ews tcell (kp,(Vint (Int.repr count), next)) p
             × malloc_token Ews tcell p.

Definition list_cell_local_facts:
  ∀ key count next p, list_cell key count next p |-- !! isptr p.
Proof. intros. unfold list_cell. Intros kp. entailer!. Qed.
#[export] Hint Resolve list_cell_local_facts: saturate_local.

Definition list_cell_valid_pointer:
  ∀ key count next p, list_cell key count next p |-- valid_pointer p.
Proof. intros. unfold list_cell. Intros kp. entailer!. Qed.
#[export] Hint Resolve list_cell_valid_pointer: valid_pointer.

练习: 1 star,标准 (listcell_fold)

Lemma listcell_fold: ∀ key kp count p' p,
    cstring Ews key kp
    × malloc_token Ews (tarray tschar (Zlength key + 1)) kp
    × data_at Ews tcell (kp, (Vint (Int.repr count), p')) p
    × malloc_token Ews tcell p
         |-- list_cell key count p' p.
Proof.
(* 在这里填写 *) Admitted.
☐
Fixpoint listrep (sigma: list (list byte × Z)) (x: val) : mpred :=
 match sigma with
 | (s,c)::hs ⇒ EX y: val, list_cell s c y x × listrep hs y
 | nil ⇒
    !! (x = nullval) && emp
 end.

练习: 2 stars,标准 (listrep_hints)

Lemma listrep_local_prop: ∀ sigma p, listrep sigma p |--
        !! (is_pointer_or_null p ∧ (p=nullval ↔ sigma=nil)).
Proof.
(* 在这里填写 *) Admitted.
#[export] Hint Resolve listrep_local_prop : saturate_local.

Lemma listrep_valid_pointer:
  ∀ sigma p,
   listrep sigma p |-- valid_pointer p.
Proof.
(* 在这里填写 *) Admitted.
#[export] Hint Resolve listrep_valid_pointer : valid_pointer.
☐
Lemma listrep_fold: ∀ key count p' p al,
  list_cell key count p' p × listrep al p' |-- listrep ((key,count)::al) p.
Proof. intros. simpl. Exists p'. cancel. Qed.
listbox 是一个指针,指向「指向 cons 单元的指针」。
Definition listboxrep al r :=
 EX p:val, data_at Ews (tptr tcell) p r × listrep al p.

Definition uncurry {A B C} (f: A → B → C) (xy: A×B) : C :=
  f (fst xy) (snd xy).

Definition hashtable_rep (contents: hashtable_contents) (p: val) : mpred :=
  EX bl: list (list (list byte × Z) × val),
    !! (contents = map fst bl) &&
    malloc_token Ews thashtable p ×
    data_at Ews thashtable (map snd bl) p
    × iter_sepcon (uncurry listrep) bl.

练习: 2 stars,标准 (hashtable_rep_hints)

Lemma hashtable_rep_local_facts: ∀ contents p,
 hashtable_rep contents p |-- !! (isptr p ∧ Zlength contents = N).
(* 在这里填写 *) Admitted.
#[export] Hint Resolve hashtable_rep_local_facts : saturate_local.

Lemma hashtable_rep_valid_pointer: ∀ contents p,
 hashtable_rep contents p |-- valid_pointer p.
(* 在这里填写 *) Admitted.
#[export] Hint Resolve hashtable_rep_valid_pointer : valid_pointer.
☐

哈希表的函数规约

Definition new_table_spec : ident × funspec :=
 DECLARE _new_table
 WITH gv: globals
 PRE [ ]
   PROP()
   PARAMS() GLOBALS(gv)
   SEP(mem_mgr gv)
 POST [ tptr thashtable ]
   EX p:val, PROP()
      RETURN (p)
      SEP(hashtable_rep empty_table p; mem_mgr gv).

Definition new_cell_spec : ident × funspec :=
 DECLARE _new_cell
 WITH s: val, key: list byte, count: Z, next: val, gv: globals
 PRE [ tptr tschar, tint, tptr tcell ]
   PROP()
   PARAMS(s; Vint (Int.repr count); next) GLOBALS(gv)
   SEP(cstring Ews key s; mem_mgr gv)
 POST [ tptr tcell ]
   EX p:val, PROP()
      RETURN(p)
      SEP(list_cell key count next p; cstring Ews key s;
          mem_mgr gv).

Definition get_spec : ident × funspec :=
 DECLARE _get
 WITH p: val, contents: hashtable_contents, s: val, sigma : list byte
 PRE [ tptr (Tstruct _hashtable noattr), tptr tschar ]
    PROP ()
    PARAMS (p; s)
    SEP (hashtable_rep contents p; cstring Ews sigma s)
 POST [ tuint ]
    PROP ( )
    RETURN (Vint (Int.repr (hashtable_get sigma contents)))
    SEP (hashtable_rep contents p; cstring Ews sigma s).

Definition incr_list_spec : ident × funspec :=
 DECLARE _incr_list
 WITH r0: val, al: list (list byte × Z), s: val,
      sigma : list byte, gv: globals
 PRE [ tptr (tptr tcell), tptr tschar ]
    PROP (list_get sigma al < Int.max_unsigned)
    PARAMS (r0; s) GLOBALS(gv)
    SEP (listboxrep al r0; cstring Ews sigma s; mem_mgr gv)
 POST [ tvoid ]
      PROP ( ) RETURN ()
      SEP (listboxrep (list_incr sigma al) r0;
           cstring Ews sigma s; mem_mgr gv).

Definition incr_spec : ident × funspec :=
 DECLARE _incr
 WITH p: val, contents: hashtable_contents, s: val,
      sigma : list byte, gv: globals
 PRE [ tptr (Tstruct _hashtable noattr), tptr tschar ]
    PROP (hashtable_get sigma contents < Int.max_unsigned)
    PARAMS (p; s) GLOBALS(gv)
    SEP (hashtable_rep contents p; cstring Ews sigma s; mem_mgr gv)
 POST [ tvoid ]
      PROP ( ) RETURN ()
      SEP (hashtable_rep (hashtable_incr sigma contents) p;
           cstring Ews sigma s; mem_mgr gv).
汇总所有 funspec
Definition Gprog : funspecs :=
        ltac:(with_library prog [
                   strcmp_spec; strcpy_spec; strlen_spec; hash_spec;
                   new_cell_spec; copy_string_spec; get_spec; incr_spec;
                   incr_list_spec
 ]).

函数 hash、copy_string、new_cell 的证明

在尝试证明 body_hash 之前, 请至少完成 Verif_strlib 中到 body_strlen 的部分。

练习: 3 stars,标准 (body_hash)

Lemma body_hash: semax_body Vprog Gprog f_hash hash_spec.
Proof.
start_function.
unfold cstring in ×.
循环不变式的 PROP 部分要维持 0 ≤ i ≤ Zlength contents。 LOCAL 部分类似这样写
    temp _c (Vbyte (Znth i (contents ++ [Byte.zero])) 而非
    temp _c (Znth i (map Vbyte (...))) 理由是 temp _c (Vint x)、temp _c (Vbyte y) 对 Floyd 来说好处理得多; 而 temp _c X 里的 X 是类型为 val 的一般公式, 处理起来麻烦得多。
循环体证明的后段会用到引理 hashfun_snoc。
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (body_copy_string)

Lemma body_copy_string: semax_body Vprog Gprog f_copy_string copy_string_spec.
Proof.
start_function.
assert_PROP (Zlength sigma + 1 ≤ Ptrofs.max_unsigned) by entailer!.
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (body_new_cell)

Lemma body_new_cell: semax_body Vprog Gprog f_new_cell new_cell_spec.
Proof.
(* 在这里填写 *) Admitted.
☐

new_table 函数的证明

关于数据结构谓词的辅助引理

练习: 2 stars,标准 (iter_sepcon_hints)

Lemma iter_sepcon_listrep_local_facts:
 ∀ bl, iter_sepcon (uncurry listrep) bl
                    |-- !! Forall is_pointer_or_null (map snd bl).
Proof.
(* 提示:使用 induction 与 sep_apply。 *)
(* 在这里填写 *) Admitted.

#[export] Hint Resolve iter_sepcon_listrep_local_facts : saturate_local.
☐

练习: 2 stars,标准 (iter_sepcon_split3)

Lemma iter_sepcon_split3:
  ∀ {A}{d: Inhabitant A} (i: Z) (al: list A) (f: A → mpred),
   0 ≤ i < Zlength al →
  (iter_sepcon f al =
   iter_sepcon f (sublist 0 i al) × f (Znth i al)
    × iter_sepcon f (sublist (i+1) (Zlength al) al))%logic.
Proof.
intros.
rewrite <- (sublist_same 0 (Zlength al) al) at 1 by auto.
(* 提示:rewrite (sublist_split LO MID HI) by lia,
    其中 LO MID HI 由你选取。
  也有用的:rewrite sublist_len_1 与 iter_sepcon_app。
  最后,你需要用到 "*" 算子的结合律与交换律:
  引理 sepcon_emp, sepcon_assoc, sepcon_comm 等。 *)

(* 在这里填写 *) Admitted.
☐

练习: 2 stars,标准 (body_new_table)

Lemma body_new_table_helper:
 (* body_new_table 的最后一步会用到这条引理 *)
 ∀ n,
  emp
  |-- iter_sepcon (uncurry listrep) (repeat ([], nullval) n).
(* 在这里填写 *) Admitted.

Lemma body_new_table: semax_body Vprog Gprog f_new_table new_table_spec.
Proof.
这个函数的循环不变式描述一个部分初始化的数组。 最好写成:
  data_at Ews thashtable
      (Zrepeat nullval i ++ Zrepeat Vundef (N-i)) p.
后面某处要证明的命题形如:
   data_at Ews thashtable
      (Zrepeat nullval (i + 1) ++ repeat Vundef (N - (i + 1))) p
其中要把
   Zrepeat nullval (i + 1) 拆成
   Zrepeat nullval i ++ Zrepeat nullval 1. 最好的办法是 rewrite <- Zrepeat_app。
(* 在这里填写 *) Admitted.
☐

get 函数的证明

练习: 2 stars,标准 (listrep_traverse)

考虑 get 函数中的这个循环:
  while (p) {
    if (strcmp(p->key, s)==0)
      return p->count;
    p=p->next;
  }
我们将在分离逻辑中用「魔杖作框架」 (Magic Wand as Frame)推理链表遍历, 论文见 https://www.cs.princeton.edu/~appel/papers/wand-frame.pdf。
循环走到链表中途时,从头到当前位置的原列表 可以看成「带洞的链表数据结构」; 而当前位置指向一个填补该洞的链表数据结构。 「带洞的数据结构」用分离蕴含表达 (称为【魔杖|Magic Wand】),即 (hole −∗ data-structure)。 它的意思是:把带洞结构与填补洞的东西合取, 就得到原数据结构:
     hole × (hole −∗ data-structure) |-- data-structure 循环之前,前置条件是:
   (listrep b0 p0; other_stuff) 几轮循环之后,情形类似:
   (listrep b p; (listrep b p −∗ listrep b0 p0); other_stuff) 循环走到 p==NULL 时,则有:
   (listrep nil nullval; (listrep nil nullval −∗ listrep b0 p0); other_stuff) 本练习中的 listrep_traverse_× 引理 分别说明怎样开始一次遍历、怎样迈出一步, 以及怎样完成一次遍历。
Lemma listrep_traverse_start:
  ∀ p al,
    emp |-- listrep al p −∗ listrep al p.
(* 在这里填写 *) Admitted.

Lemma listrep_traverse_step:
  ∀ al key count p' p,
  list_cell key count p' p |--
     listrep al p' −∗ listrep ((key, count) :: al) p.
(* 在这里填写 *) Admitted.

Lemma listrep_traverse_step_example:
 ∀ kp key count al q p b0 p0,
    cstring Ews key kp ×
    (listrep ((key, count) :: al) p −∗ listrep b0 p0) ×
    malloc_token Ews (tarray tschar (Zlength key + 1)) kp ×
    data_at Ews tcell (kp, (Vint (Int.repr count), q)) p ×
    malloc_token Ews tcell p ×
    listrep al q
  |-- listrep b0 p0.
Proof.
intros.
提示:用 sep_apply 配合引理 listcell_fold、 listrep_traverse_step、wand_frame_ver、 modus_ponens_wand。
(* 在这里填写 *) Admitted.

Lemma listrep_traverse_finish:
 ∀ al p,
   listrep nil nullval × (listrep nil nullval −∗ listrep al p)
  |-- listrep al p.
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (body_get)

适当使用 listrep_traverse_× 引理。
Lemma body_get: semax_body Vprog Gprog f_get get_spec.
Proof.
start_function.
rename p into table.
pose proof (hashfun_inrange sigma).

unfold abbreviate in MORE_COMMANDS; subst MORE_COMMANDS.
下一条命令在普通的可验证 C 证明中不会出现; 它只是帮你把大证明推进一步。
apply seq_assoc1; assert_after 1
 (EX cts:list (list (list byte × Z) × val),
  PROP (contents = map fst cts )
  LOCAL (temp _h (Vint (Int.repr (hashfun sigma)));
         temp _table table; temp _s s)
  SEP (cstring Ews sigma s; malloc_token Ews thashtable table;
       data_at Ews thashtable (map snd cts) table;
       iter_sepcon (uncurry listrep) cts))%assert.
{
 (* 在这里填写 *) admit.
}
Intros cts; subst contents.
forward.
deadvars!.

autorewrite with norm.
上一行的 autorewrite 之所以有效, 全靠假设 H。换成 clear H; autorewrite with norm, 就会看到 Int.modu 并没被消去。
rewrite <- N_eq.
这次改写是为了在证明中保留一点抽象。 N_eq 在 rep_lia 提示数据库里, 所以 rep_lia 「知道」N=109。
assert (0 ≤ hashfun sigma mod N < N).
这类事实放在横线上方很有用, rep_lia 要靠它在 Z 与 Int 之间转换。
  (* 在这里填写 *) admit.
assert_PROP (Zlength cts = N) as H1.
这类等式放在横线上方,list_solve、 rep_lia 以及调用它们的 entailer! 都用得上。
{
 (* 在这里填写 *) admit.
}
forward.
这个证明目标从哪来?denote_tc_assert 是一个 「类型检查断言」:证明某个 C 表达式求值时不会崩溃。 这里的表达式是 table→buckets[b], 为此要证明 b 在数组界内, 且数组的第 b 个元素确实已初始化。
上面证出的假设 H1 通常很有用, 此处尤其如此。
 { (* 在这里填写 *) admit.
 }
set (h := hashfun sigma mod N) in ×.
下一条命令在普通的可验证 C 证明中不会出现; 它只是帮你把大证明推进一步。
eapply semax_pre; [ instantiate (1:=
  PROP ( ) LOCAL (temp _p (snd (Znth h cts)); temp _s s)
  SEP (cstring Ews sigma s; malloc_token Ews thashtable table;
       data_at Ews thashtable (map snd cts) table;
       iter_sepcon (uncurry listrep) (sublist 0 h cts);
        listrep (fst (Znth h cts)) (snd (Znth h cts));
       iter_sepcon (uncurry listrep) (sublist (h + 1) (Zlength cts) cts))) | ].
{ (* 在这里填写 *) admit.
}

destruct (Znth h cts) as [b0 p0] eqn:Hbp0.
simpl.
接下来是沿链表下走的 while 循环。 指针 p0 指向表示序列 b0 的列表开头。 循环每走一步,p 就沿链接下移一格, 指向更短的序列 b。
从 p0 到 p 的列表段,用魔杖公式表示: listrep b p −∗ listrep b0 p0。 它表示一个【堆片|Heaplet】(内存片段): 把它与表示 listrep b p 的堆片拼起来, 得到的就是整个 listrep b0 p0。
有若干 SEP 合取项,循环结束前还用不上。 可以用这条命令把它们暂存到单个 SEP 合取项 FRZL FR1 里:
freeze FR1 := (malloc_token _ _ table) (data_at _ _ _ table)
       (iter_sepcon _ _) (iter_sepcon _ _).
freeze 策略把若干合取项先「框架」出去, 等以后 thaw FR1 再取回。
forward_while
 (EX b: list (list byte × Z), EX p: val,
    PROP( (* 在此填写 b 与 b0 的关系。
          特别是:沿列表走过与 sigma
          不匹配的键时,list_get sigma
          的结果不变。 *)

          
        )
    LOCAL (temp _p p; temp _s s)
    SEP (FRZL FR1; cstring Ews sigma s
           (* 在此填写循环不变式的其余部分!
             其中一个合取项应是描述带洞数据结构的
             魔杖表达式;另一个合取项描述洞中放什么。 *)

           
        )).
× (* 前置条件蕴含循环不变式 *)
(* 在这里填写 *) admit.
× (* 循环测试表达式不崩溃 *)
(* 在这里填写 *) admit.
× (* 循环体保持循环不变式 *)
 
和通常的链表遍历一样,我们要解引用 p→key, 手头却没有 p 的 data_at 合取项,只有 listrep b p。 所以必须展开 listrep;而展开只有在知道 p≠nil 时才有用。 于是分类讨论:
destruct b as [ | [key count] al].
b=nil 不可能。前提是你有正确的循环不变式: 前置条件 SEP 子句里的某些信息, 与横线上方的 HRE: isptr p 对不上。 要用 SEP 子句中的命题信息,请用 assert_PROP:
 {
   assert_PROP False. {
   (* 在这里填写 *) admit.
   }
   contradiction.
 }
idtac.
这个 * 子项余下部分的结构如下:
  • 整理前置条件,完成到函数 strcmp 的 forward_call。
  • 做 forward_if (vret≠Int.zero)。传给 forward_if 的实参可以只是 Prop, 不必是完整的 PROP/LOCAL/SEP,因为:
    • if 的一个分支永远到不了汇合点,它直接返回;
    • if 的另一个分支不改任何局部变量或内存, 断言的 LOCAL 与 SEP 部分原封不动。
    • 子项:then 子句。 证明中某处要 thaw FR1, 还要用 iter_sepcon_split3。 then 子句末尾附近,目标会与 listrep_traverse_step_example 相似 (未必完全相同)。
    • 子项:else 子句,短小直截。
    • 子项:if 之后;又一个与 listrep_traverse_step_example 相似的目标。
(* 在这里填写 *) admit.
× (* 循环之后 *)
  
此处仍有一个带洞的数据结构,由 (A −∗ B) 表示;洞里的东西由 A 表示。 这与 listrep_traverse_finish 相似。
  (* 在这里填写 *) admit.
(* 在这里填写 *) Admitted.
☐

incr_list 函数的证明

上面 get 的证明只是遍历链表,不改动它。 循环不变式形如 listrep b p × (listrep b p −∗ listrep b0 p0)。
incr_list 却要修改链表, 可能还在末尾插入新元素。另外,C 程序的 循环变量 struct cell **r 是 指向「指向链表单元的指针」的指针。 分离逻辑里用 listboxrep 描述它。
Print listboxrep. (* = fun (al : list (list byte * Z)) (r : val) =>
     EX p : val, data_at Ews (tptr tcell) p r * listrep al p   *)

换言之,r 是一个装着指针 p 的单字盒子, 而 p 是一个 listrep。 来看要验证的这个循环:
void incr_list (struct cell **r0, char *s) {
  struct cell *p, **r;
  for(r=r0; ; r=&p->next) {
    p = *r;
    if (!p) { *r = new_cell(s,1,NULL); return; }
    if (strcmp(p->key, s)==0) {p->count++; return;}
} }
变量 r 这样描述:
  PROP() LOCAL(temp _r r) SEP(data_at Ews (tptr tcell) q r). 也就是一个指向「装着 q 的单字」的指针。 但执行 r = &(p→next) 之后, r 指向 struct cell 记录中部的 next 字段。要单独描述这一个字段, 先用 unfold_data_at 把
  data_at Ews tcell (x,y,q) p 拆成四个独立的合取项:
  field_at Ews tcell [StructField _key] x p ×
  field_at Ews tcell [StructField _count] y p ×
  spacer Ews (nested_field_offset tcell [StructField _count] + sizeof tuint)
                       (nested_field_offset tcell [StructField _next]) p ×
  field_at Ews tcell [StructField _next] q p
再把最后一个合取项改写成
  data_at Ews (tptr tcell) q (field_address tcell [StructField _next] p) 这里 (field_address _ _ _) 是「地址算术」表达式, 描述从 p 到 &(p→next) 的字节偏移。
「spacer」解释字段之间的填充。 在 32 位整数、32 位指针的配置下, 这个特定 spacer 化简为 emp。 但在 32 位整数、64 位指针的配置下, spacer 相当于 4 字节的 Vundef 填充。
listboxrep_traverse 引理刻画循环体结束时的状态。 看 |-- 左边:变量 r 指向装着 p 的单字 (它或许是前一个链表单元的 _next 字段)。 变量 p 指向一个被拆开的链表单元, 只带 _key 与 _count 字段。 p 的 _next 字段在哪?我们偏不在这个堆片里描述它!
右边说的是:在地址 &p→next 处给出一个堆片, 它满足 listboxrep、表示序列 dl; 那么拼接后的堆片就在地址 r 处满足 listboxrep, 表示序列 (key,count)::dl。 而且这对【任何】序列 dl 都成立。 于是程序可以随意改 p→next 的内容, 也可以改序列中靠后的任何 _next 字段。

练习: 3 stars,标准 (listboxrep_traverse)

Lemma listboxrep_traverse:
  ∀ p kp key count r,
     cstring Ews key kp ×
     malloc_token Ews (tarray tschar (Zlength key + 1)) kp ×
     field_at Ews tcell [StructField _key] kp p ×
     field_at Ews tcell [StructField _count] (Vint (Int.repr count)) p ×
     spacer Ews (nested_field_offset tcell [StructField _count] + sizeof tuint)
                       (nested_field_offset tcell [StructField _next]) p ×
     malloc_token Ews tcell p ×
     data_at Ews (tptr tcell) p r
   |--
     ALL dl: list (list byte × Z),
       listboxrep dl (field_address tcell [StructField _next] p)
       −∗ listboxrep ((key, count) :: dl) r.
Proof.
  intros.
  simpl spacer.
 apply allp_right; intro dl.
 apply → wand_sepcon_adjoint.
下面的证明里,你会遇到 data_at Ews tcell ... p, 想把它展开成
       field_at Ews tcell [StructField _key] ... p
     × field_at Ews tcell [StructField _count] ... p
     × field_at Ews tcell [StructField _next] ... p].
用 unfold_data_at (pattern) 即可, pattern 类似 (data_at _ _ _ p), 指明要展开哪个 SEP 合取项。
之后再用 field_at_data_at 改写……
Check (field_at_data_at Ews tcell [StructField _next]). (* =
  forall v p, 
       field_at Ews tcell StructField _next v p =
       data_at Ews (nested_field_type tcell StructField _next) v
         (field_address tcell StructField _next p). *)

Eval simpl in (nested_field_type tcell [StructField _next]).
  (* = tptr (Tstruct _cell noattr) *)

(* 在这里填写 *) Admitted.
☐
32 位配置下 spacer 等价于 emp, 这个 listboxrep_traverse 的特化版本很好用。
Lemma listboxrep_traverse32:
  ∀ p kp key count r,
     Archi.ptr64 = false →
     cstring Ews key kp ×
     malloc_token Ews (tarray tschar (Zlength key + 1)) kp ×
     field_at Ews tcell [StructField _key] kp p ×
     field_at Ews tcell [StructField _count] (Vint (Int.repr count)) p ×
     malloc_token Ews tcell p ×
     data_at Ews (tptr tcell) p r
   |--
     ALL dl: list (list byte × Z),
       listboxrep dl (field_address tcell [StructField _next] p)
       −∗ listboxrep ((key, count) :: dl) r.
Proof.
intros.
inv H; (* 若我们在 64 位模式下则解决目标 *)
(* 否则我们在 32 位模式下 *)
(eapply derives_trans; [ | apply (listboxrep_traverse p kp key count r)];
 unfold spacer; simpl; cancel).
Qed.

练习: 4 stars,标准 (body_incr_list)

Lemma body_incr_list: semax_body Vprog Gprog f_incr_list incr_list_spec.
Proof.
这个证明用「魔杖作框架」遍历【并更新】 一个(链表)数据结构。它比 body_get 中的 魔杖作框架模式稍复杂;那个模式不更新结构。 「带洞的数据结构」与「洞中放什么」照旧要用; 不同的是,带洞结构现在要能接受【未来】的填洞者, 而非此刻已在洞中的那个。
关键引理是 wand_refl_cancel_right、 wand_frame_elim' 与 wand_frame_ver。 用 wand_frame_ver 时,listboxrep_traverse 或 listboxrep_traverse32 会派上用场。
(* 在这里填写 *) Admitted.
☐

field_compatible

下面讨论怎样寻址结构体的各个字段, 或数组的各个槽。
首先,data_at sh (Tstruct _ _) 等价于 各字段单独的 field_at 谓词合取。 (数组同理。)
Lemma example_split_struct:
 ∀ p (x y z: val),
      data_at Ews tcell (x,(y,z)) p
   = (field_at Ews tcell [StructField _key] x p
     × field_at Ews tcell [StructField _count] y p
     × spacer Ews (nested_field_offset tcell [StructField _count] + sizeof tuint)
                       (nested_field_offset tcell [StructField _next]) p
     × field_at Ews tcell [StructField _next] z p)%logic.
Proof.
intros.
unfold_data_at (data_at _ _ _ p).
unfold spacer; simpl; rewrite ?sepcon_emp. (* 32 位模式下需要此行,64 位模式下无害 *)
rewrite !sepcon_assoc.
reflexivity.
Qed.
其次,field_at sh t gfs z p 等价于 data_at sh (tptr t) z (field_address t gfs p)。 field_address 描述的是一段以字节计的偏移: 从结构体基址量到该结构体某个字段的地址; 数组元素也一样。
Lemma example_field_at_data_at:
 ∀ p (z: val),
   field_at Ews tcell [StructField _next] z p =
   data_at Ews (tptr tcell) z
    (field_address tcell [StructField _next] p).
Proof.
intros.
 rewrite field_at_data_at.
 reflexivity.
Qed.
struct cell 的 _next 排在两个整数字段之后, 是第三个字段。这些字段之间没有填充 (这里正是如此),所以从结构体基址到 _next 字段基址的距离应为 2*sizeof(tint)。
Lemma example_field_at_data_at':
 ∀ p (z: val),
   field_at Ews tcell [StructField _next] z p |--
   data_at Ews (tptr tcell) z
    (offset_val (2 × sizeof size_t) p).
Proof.
intros.
 rewrite field_at_data_at.
 unfold field_address.
 if_tac; simpl; auto.
 cancel.
 entailer!.
 destruct H0 as [H0 _].
 contradiction H0.
Qed.
但逆命题不成立:
Lemma example_field_at_data_at'':
 ∀ p (z: val),
   data_at Ews (tptr tcell) z
    (offset_val (2 × sizeof size_t) p)
 |-- field_at Ews tcell [StructField _next] z p.
Proof.
 intros.
 rewrite field_at_data_at.
 simpl.
 unfold field_address.
 rewrite if_true.
 simpl.
 cancel.
 (* 不可证! *)
Abort.
不过,再加一条前提就能证它:
Lemma example_field_at_data_at''':
 ∀ p (z: val),
  field_compatible tcell [StructField _next] p →
   data_at Ews (tptr tcell) z
    (offset_val (2 × sizeof size_t) p)
 |-- field_at Ews tcell [StructField _next] z p.
Proof.
 intros.
 rewrite field_at_data_at.
 simpl.
 unfold field_address.
 rewrite if_true by assumption.
 simpl.
 cancel.
Qed.
为什么?答案在 field_address 的定义里:
Print field_address. (* = 
   fun {cs : compspecs} (t : type) (gfs : list gfield) (p : val) =>
    if field_compatible_dec t gfs p 
    then offset_val (nested_field_offset t gfs) p 
    else Vundef *)

这说明:field_compatible t gfs p 成立时, 字段地址是(例如) offset_val (2 × sizeof tint) p; 而 ¬ field_compatible t gfs p 时, 地址是 Vundef。 也就是说,field_address t gfs p 只有在地址 p 与 t、gfs 相容时才有定义。 什么是 field_compatible?
设 p 是一个地址,t 是一个 C 语言类型。 我们可能会问:把类型 t 的对象 放在地址 p 处是否合法?并不总是! 需要满足这些条件:
  • isptr p:p 必须是指针值(Vptr), 而非整数或未定义值。
  • complete_legal_cosu_type t = true: t 必须是完整的。例如若写 typedef struct foo ×t, 就必须有 struct foo 的定义。
  • size_compatible t p:从 p 起 至少要有 sizeof t 字节,不能越过最大地址。
  • align_compatible t p:p 必须是 2、4 或 8 的适当倍数(视需要而定), 好让类型 t 的每个子字段 都按自己的数据类型对齐。
  • legal_nested_field t gfs:若问「把带字段 路径 gfs 的类型 t 对象放在 p 处是否合法?」, 还得知道 gfs 是类型 t 中可能的字段路径。 例如 StructField _count 是类型 tcell 的 合法路径,而 StructField _s 不是, 因为没有这个字段。
    关于 t, p, gfs 的这些性质, 全部封装在谓词 field_compatible 里:
Print field_compatible. (* = 
  fun {cs : compspecs} (t : type) (gfs : list gfield) (p : val) =>
  isptr p /\
  complete_legal_cosu_type t = true /\
  size_compatible t p /\
  align_compatible t p /\
  legal_nested_field t gfs  *)

_count 是 struct cell 的一个字段
Goal (legal_nested_field tcell [StructField _count]).
compute; auto 10.
Qed.
_s 不是 struct cell 的字段
Goal (~ legal_nested_field tcell [StructField _s]).
compute. intuition congruence.
Qed.
0 是 struct cell ×a[109] 的合法下标
Goal (legal_nested_field (tarray (tptr tcell) 109) [ArraySubsc 0]).
compute. intuition congruence.
Qed.
108 是 struct cell ×a[109] 的合法下标
Goal (legal_nested_field (tarray (tptr tcell) 109) [ArraySubsc 108]).
compute. intuition congruence.
Qed.
109 不是 struct cell ×a[109] 的合法下标
Goal (~ legal_nested_field (tarray (tptr tcell) 109) [ArraySubsc 109]).
compute. intuition congruence.
Qed.
C 里有时想要一个【恰好落在数组末尾】的指针。 给定 struct cell ×a[109], 我们想要指针值 &a[109] 。 这是合法的,哪怕数组并不存在这一槽。
为此需要 legal_nested_field 的一个变体, 它允许「恰好在末尾」:
Check legal_nested_field0. (* : type -> list gfield -> Prop *)
108 是 struct cell ×a[109] 的可寻址下标
Goal (legal_nested_field0 (tarray (tptr tcell) 109) [ArraySubsc 108]).
compute. intuition congruence.
Qed.
109 是 struct cell ×a[109] 的可寻址下标
Goal (legal_nested_field0 (tarray (tptr tcell) 109) [ArraySubsc 109]).
compute. intuition congruence.
Qed.
110 不是 struct cell ×a[109] 的可寻址下标
Goal (~ legal_nested_field (tarray (tptr tcell) 109) [ArraySubsc 110]).
compute. intuition congruence.
Qed.
基于这两个概念,
  • legal_nested_field(可加载/可存储字段)与
  • legal_nested_field0(可寻址字段),
我们分别有 field_compatible 与 field_compatible0。
Print field_compatible0. (* = 
  fun {cs : compspecs} (t : type) (gfs : list gfield) (p : val) =>
  isptr p /\
  complete_legal_cosu_type t = true /\
  size_compatible t p /\
  align_compatible t p /\
  legal_nested_field0 t gfs  *)

field_compatible 从哪来?

再看这条引理:
Check example_field_at_data_at'''. (* : forall p (z: val),
  field_compatible tcell StructField _next p ->
   data_at Ews (tptr tcell) z 
    (offset_val (2 * sizeof tint) p)
 |-- field_at Ews tcell StructField _next z p. *)

field_compatible... 若在横线上方, 就能应用这条引理。 怎样把它弄到横线上方? entailer 或 entailer! 通常会自动做到: 它们从左边 SEP 子句里的 data_at 或 field_at 事实推出这条假设。

incr 函数的证明

  void incr_list (struct cell **r0, char *s);

  void incr (struct hashtable *table, char *s) {
    unsigned int h = hash(s);
    unsigned int b = h % N;
    incr_list (& table->buckets[b], s);
  }
难点在函数实参 & table→buckets[b] 。 incr_list 的前置条件只要求一个「单元指针的指针」, 我们手里却是一整个数组,装着 109 个单元指针。
起点是 table:它指向一个结构体, 该结构体有一个字段,是一条 109 元素的数组。 调用 incr_list 前,要把它拆成 两个独立的数据结构:
  • table→buckets+b 处的单元素数组
  • 数据结构的其余全部,包括 struct hashtable 的其他字段(若有的话),以及数组的 元素 0..b-1 与 b+1..108。
wand_slice_array 引理能做到这一点:
Check wand_slice_array.
(*  : forall (lo hi n : Z) (t : type) (sh : Share.t)
             (al : list (reptype t)) (p : val),
       0 <= lo <= hi ->
       hi <= n ->
       Zlength al = n ->
       data_at sh (tarray t n) al p =
       !! field_compatible (tarray t n)  p &&
       data_at sh (tarray t (hi - lo)) (sublist lo hi al)
         (field_address0 (tarray t n) ArraySubsc lo p) *
       array_with_hole sh t lo hi n al p.
*)

这里 (array_with_hole sh t lo hi n al p) 表示
Print array_with_hole.
(*  : !! field_compatible (tarray t n)  p &&
      (ALL cl : list (reptype t) ,
         data_at sh (tarray t (hi - lo)) cl
           (field_address0 (tarray t n) ArraySubsc lo p) −∗
         data_at sh (tarray t n)
           (sublist 0 lo al' ++ cl ++ sublist hi n al') p)
*)

这表示 data_at sh (tarray t n) al p 可以拆成两片:
  • 1. 从下标 lo 到下标 hi-1 的切片,
  • 2. 其余全部。
后面 body_incr 的证明里,要处理函数实参 & (table→buckets[b]) ,其中变量 _b 取值 h。 CompCert 把它算成 table + (sizeof int)*h,即
    offset_val (sizeof (tptr tcell) × h) table 我们却想写成 [ field_address0 (tarray (tptr tcell) N) [ArraySubsc h] (field_address thashtable [StructField _buckets] table). ] 如上文 field_compatible 一节所说, 要证出一个 field_address,先要知道两件事: 地址 table 与 thashtable 字段相容; 地址 table→buckets 与 ArraySubsc h 也相容。 下面这条引理把两者都证了:
Lemma body_incr_field_address_lemma:
  ∀ (table: val) (h : Z),
  0 ≤ h < N →
  field_compatible (tarray (tptr tcell) N) []
    (field_address thashtable [StructField _buckets] table) →
  field_compatible (tptr tcell) []
    (field_address0 (tarray (tptr tcell) N)
       [ArraySubsc h]
       (field_address thashtable [StructField _buckets] table)) →
  offset_val (sizeof (tptr tcell) × h) table =
  field_address0 (tarray (tptr tcell) N) [ArraySubsc h]
    (field_address thashtable [StructField _buckets] table).
Proof.
  intros.
提示数据库让 auto with field_compatible 能用上横线上方的 field_compatible 事实。
  rewrite field_address0_offset by auto with field_compatible.
  rewrite field_address_offset by auto with field_compatible.
  autorewrite with norm. auto.
Qed.
提示:研究这条引理及其证明, 弄清它的含义。
Lemma data_at_thashtable_tarray:
 ∀ al table,
    data_at Ews thashtable al table
    |-- data_at Ews (tarray (tptr tcell) N) al
           (field_address thashtable [StructField _buckets] table).
Proof.
intros.
unfold_data_at (data_at _ _ _ table).
rewrite field_at_data_at.
simpl.
apply derives_refl.
Qed.

练习: 4 stars,标准 (body_incr)

Lemma body_incr: semax_body Vprog Gprog f_incr incr_spec.
Proof.
start_function.
rename p into table.
rename H into Hmax.
assert_PROP (isptr table) as Htable by entailer!.
接下来两行在普通的可验证 C 证明中不会出现; 它们只是帮你推进这个大证明。
subst MORE_COMMANDS; unfold abbreviate; match goal with ⊢ semax _ _ (Ssequence ?c1 (Ssequence ?c2 ?c3)) _ ⇒ apply (semax_unfold_seq (Ssequence (Ssequence c1 c2) c3)); [ reflexivity | ] end.
pose (j := EX cts: list (list (list byte × Z) × val), PROP (contents = map fst cts; 0 ≤ hashfun sigma mod N < N; Zlength cts = N) LOCAL (temp _b (Vint (Int.repr (hashfun sigma mod N))); temp _h (Vint (Int.repr (hashfun sigma))); temp _table table; temp _s s; gvars gv) SEP (cstring Ews sigma s; malloc_token Ews thashtable table; data_at Ews (tarray (tptr tcell) N) (map snd cts) (field_address thashtable [StructField _buckets] table); iter_sepcon (uncurry listrep) cts; mem_mgr gv)); apply semax_seq' with j; subst j; abbreviate_semax.
{
 (* 在这里填写 *) admit.
 }

Intros cts.
subst contents.
unfold hashtable_get in Hmax.
rewrite Zlength_map, H1 in Hmax.
set (h := hashfun sigma mod N) in ×.
erewrite (wand_slice_array h (h+1) N _ (tptr tcell))
  by first [rep_lia | list_solve ].
对证明的其余部分,这里有一些有用的引理: sublist_len_1、sublist_same、sublist_map、 data_at_singleton_array_eq、 iter_sepcon_split3、iter_sepcon_app、 sublist_split、field_at_data_at、 wand_slice_array_tptr_tcell
(* 在这里填写 *) Admitted.
☐
(* 2026-11-26 16:01 *)