Equiv程序等价

Set Warnings "-notation-overridden".
From PLF Require Import Maps.
From Stdlib Require Import Bool.
From Stdlib Require Import Arith.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import PeanoNat. Import Nat.
From Stdlib Require Import EqNat.
From Stdlib Require Import Lia.
From Stdlib Require Import List. Import ListNotations.
From Stdlib Require Import FunctionalExtensionality.
From PLF Require Export Imp.

开始之前:

  • 为本卷创建一个全新的目录。不要试图把本卷的文件与 【《逻辑基础》】的文件混在同一目录中:结果不会令你满意。
    你可以先从一个空目录开始,把下面列出的文件(以及之后陆续 需要的其它文件)放进去;也可以下载整个 PLF 压缩包并解压。
  • 新目录中应至少包含以下文件:
    • Imp.v(确保用的是 PLF 发行版中的那份,而非 LF 中的: 二者略有不同);
    • Maps.v(同上)
    • Equiv.v(本文件)
    • _CoqProject,其中包含如下一行:
                 -Q . PLF
  • 如果你看到类似这样的错误……
               Compiled library PLF.Maps (in file .../plf/Maps.vo)
               makes inconsistent assumptions over library Rocq.Init.Logic
    ……可能意味着上述步骤出了问题。 执行 make clean(或手动删除除 .v 和 _CoqProject 之外的所有文件)也许有帮助。
  • 如果你使用带 VSCoq 扩展的 VSCode,接下来要在 VSCode 中 打开一个新窗口,点击 Open Folder > plf,然后运行 make。 若出现「Cannot find a physical path...」之类的错误, 可能是因为你没有直接打开 plf 文件夹。 (比如你打开的是同时包含 lf 和 plf 的上层文件夹。)

关于做习题的建议:

  • 本章要求你完成的大多数 Rocq 证明, 都与我们已经给出的证明类似。 开始做习题之前,请先花时间通读我们的证明 (无论非形式化的还是 Rocq 中的)。 确保你完全理解它们的细节,这会省下大量力气。
  • 现在的 Rocq 证明已经足够复杂, 几乎不可能靠随机尝试或凭直觉完成。 你需要先有一个想法:这个性质为何为真, 证明将如何展开。 最好在形式化证明之前, 至少在纸上写出非形式化证明的草稿, 直观地说服自己定理为真。 或者拉上朋友,先说服他们定理成立, 再把你的解释形式化。
  • 用自动化来节省力气!本章的证明若把所有情况全部显式写出, 会变得相当长。

行为等价

前面的章节考察了一个很简单的程序变换的正确性: optimize_0plus 函数。 那里考虑的语言是算术表达式语言的第一版,没有变量。 在那种设定下,正确性很容易定义: 变换应当总是产生一个与原程序求值得到相同数字的程序。
为讨论完整 Imp(尤其是赋值)中程序变换的正确性, 需要考虑可变状态所扮演的角色。 并发展更精细的正确性概念, 即【行为等价|Behavioral Equivalence】。
例如:
  • X + 2 与 1 + X + 1 行为等价
  • X - X 与 0 行为等价
  • (X - 1) + 1 与 X 【不】 行为等价

定义

对含变量的 aexp 与 bexp,定义很清楚: 两个 aexp 或 bexp 是「行为等价」的, 当且仅当它们在每个状态下都求值得到相同结果。
Definition aequiv (a1 a2 : aexp) : Prop :=
  ∀ (st : state),
    aeval st a1 = aeval st a2.

Definition bequiv (b1 b2 : bexp) : Prop :=
  ∀ (st : state),
    beval st b1 = beval st b2.
下面是一些算术与布尔表达式等价的简单示例。
Theorem aequiv_example:
  aequiv
    <{ X - X }>
    <{ 0 }>.
Proof.
  intros st. simpl. lia.
Qed.

Theorem bequiv_example:
  bequiv
    <{ X - X = 0 }>
    <{ true }>.
Proof.
  intros st. unfold beval.
  rewrite aequiv_example. reflexivity.
Qed.
对命令而言,情形要微妙一些。 不能简单地说「两个命令行为等价, 当且仅当它们从相同的初始状态开始时 求值到相同的结束状态」。 因为有些命令在某些起始状态下运行时, 根本不会在任何最终状态下终止!
实际需要的是:两个命令行为等价, 当且仅当对任何起始状态, 它们要么 (1) 都发散, 要么 (2) 都终止于相同最终状态。 一种简洁的说法是: 「若第一个在某个特定状态终止, 则第二个也在该状态终止,反之亦然。」
Definition cequiv (c1 c2 : com) : Prop :=
  ∀ (st st' : state),
    (st =[ c1 ]=> st') ↔ (st =[ c2 ]=> st').

简单示例

作为命令等价的示例,我们先看一条涉及 skip 的平凡等价:
Theorem skip_left : ∀ c,
  cequiv
    <{ skip; c }>
    c.
Proof.
  (* 已在课上完成 *)
  intros c st st'.
  split; intros H.
  - (* -> *)
    inversion H. subst.
    inversion H2. subst.
    assumption.
  - (* <- *)
    apply E_Seq with st.
    + apply E_Skip.
    + assumption.
Qed.

练习: 2 stars,标准 (skip_right)

证明在一条命令【之后】添加 skip 得到的程序同样等价
Theorem skip_right : ∀ c,
  cequiv
    <{ c; skip }>
    c.
Proof.
  (* 在这里填写 *) Admitted.
☐
类似地,下面是一条优化 if 命令的简单等价:
Theorem if_true_simple : ∀ c1 c2,
  cequiv
    <{ if true then c1 else c2 end }>
    c1.
Proof.
  intros c1 c2.
  split; intros H.
  - (* -> *)
    inversion H; subst.
    + assumption.
    + discriminate.
  - (* <- *)
    apply E_IfTrue.
    + reflexivity.
    + assumption. Qed.
当然,没有程序员会写出条件字面上就是 true 的条件分支。 (至少人类程序员不会,编译器和宏预处理器内部倒总是做这类事!) 但他们可能写出条件【等价于】 true 的条件分支:
【定理】:若 b 等价于 true,则 if b then c1 else c2 end 等价于 c1。
【证明】:
  • (→) 我们必须证明,对所有 st 和 st',若 st =[ if b then c1 else c2 end ]=> st' 则 st =[ c1 ]=> st'。
    对可能用于推出 st =[ if b then c1 else c2 end ]=> st' 的规则 分类讨论,即 E_IfTrue 和 E_IfFalse。
    • 假设 st =[ if b then c1 else c2 end ]=> st' 的导出式 最后用的规则是 E_IfTrue。那么由 E_IfTrue 的前提即得 st =[ c1 ]=> st',这正是我们要证明的。
    • 另一方面,假设该导出式最后用的规则是 E_IfFalse。 于是我们知道 beval st b = false 且 st =[ c2 ]=> st'。
      回顾 b 等价于 true,即对所有 st, beval st b = beval st <{true}> 。特别地,由于 beval st <{true}> = true,这意味着 beval st b = true。 但这与 E_IfFalse 要求的 beval st b = false 矛盾。 因此最后一步不可能是 E_IfFalse。
  • (<-) 我们必须证明,对所有 st 和 st',若 st =[ c1 ]=> st' 则 st =[ if b then c1 else c2 end ]=> st'。
    由于 b 等价于 true,我们知道 beval st b = beval st <{true}> = true。结合 st =[ c1 ]=> st' 这一假设, 我们可以应用 E_IfTrue 推出 st =[ if b then c1 else c2 end ]=> st'。 ☐
下面是这一证明的形式化版本:
Theorem if_true: ∀ b c1 c2,
  bequiv b <{true}> →
  cequiv
    <{ if b then c1 else c2 end }>
    c1.
Proof.
  intros b c1 c2 Hb.
  split; intros H.
  - (* -> *)
    inversion H; subst.
    + (* b 求值为 true *)
      assumption.
    + (* b 求值为 false(矛盾) *)
      unfold bequiv in Hb. simpl in Hb.
      rewrite Hb in H5.
      discriminate.
  - (* <- *)
    apply E_IfTrue; try assumption.
    unfold bequiv in Hb. simpl in Hb.
    apply Hb. Qed.

练习: 2 stars,标准,特别有用 (if_false)

Theorem if_false : ∀ b c1 c2,
  bequiv b <{false}> →
  cequiv
    <{ if b then c1 else c2 end }>
    c2.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (swap_if_branches)

表明如果我们同时对条件取反,就可以交换 if 的两个分支。
Theorem swap_if_branches : ∀ b c1 c2,
  cequiv
    <{ if b then c1 else c2 end }>
    <{ if ¬ b then c2 else c1 end }>.
Proof.
  (* 在这里填写 *) Admitted.
☐
对 while 循环,可以给出一对类似的定理。 守卫等价于 false 的循环等价于 skip。 守卫等价于 true 的循环等价于 while true do skip end(或任何其它不终止的程序)。
这两条事实中,第一条很容易。
Theorem while_false : ∀ b c,
  bequiv b <{false}> →
  cequiv
    <{ while b do c end }>
    <{ skip }>.
Proof.
  intros b c Hb. split; intros H.
  - (* -> *)
    inversion H; subst.
    + (* E_WhileFalse *)
      apply E_Skip.
    + (* E_WhileTrue *)
      rewrite Hb in H2. discriminate.
  - (* <- *)
    inversion H. subst.
    apply E_WhileFalse.
    apply Hb. Qed.

练习: 2 stars,高级,可选 (while_false_informal)

写出 while_false 的非形式化证明。
(* 在这里填写 *)
☐
为了证明第二条事实,我们需要一条辅助引理:守卫条件等价于 true 的 while 循环永不终止。
【引理】:若 b 等价于 true,则不可能有 st =[ while b do c end ]=> st'。
【证明】:假设 st =[ while b do c end ]=> st'。我们对 st =[ while b do c end ]=> st' 的导出式归纳,证明该假设 会导致矛盾。只有 E_WhileFalse 和 E_WhileTrue 两种情况 需要考虑;其余情况自相矛盾。
  • 假设 st =[ while b do c end ]=> st' 用规则 E_WhileFalse 证明。那么由假设 beval st b = false。但这与 b 等价于 true 的假设矛盾。
  • 假设 st =[ while b do c end ]=> st' 用规则 E_WhileTrue 证明。我们必有:
    1. beval st b = true,以及 2. 存在某个 st0 使得 st =[ c ]=> st0 且 st0 =[ while b do c end ]=> st'。 3. 此外,我们还有一个归纳假设,说明 st0 =[ while b do c end ]=> st' 会导致矛盾,
由 2 和 3 即得矛盾。☐
Lemma while_true_nonterm : ∀ b c st st',
  bequiv b <{true}> →
  ~( st =[ while b do c end ]=> st' ).
Proof.
  (* 已在课上完成 *)
  intros b c st st' Hb.
  intros H.
  remember <{ while b do c end }> as cw eqn:Heqcw.
  induction H;
  (* 大多数规则不适用;我们用反演把它们排除: *)
  inversion Heqcw; subst; clear Heqcw.
  (* 有趣的是这两个关于 while 循环的情况: *)
  - (* E_WhileFalse *) (* 矛盾:b 总为真! *)
    unfold bequiv in Hb.
    (* rewrite 能实例化 st 中的量词 *)
    rewrite Hb in H. discriminate.
  - (* E_WhileTrue *) (* 由归纳假设立得 *)
    apply IHceval2. reflexivity. Qed.

练习: 2 stars,标准,可选 (while_true_nonterm_informal)

解释引理 while_true_nonterm 的含义。
(* 在这里填写 *)
☐

练习: 2 stars,标准,特别有用 (while_true)

证明以下定理。【提示】:这里你会想用 while_true_nonterm。
Theorem while_true : ∀ b c,
  bequiv b <{true}> →
  cequiv
    <{ while b do c end }>
    <{ while true do skip end }>.
Proof.
  (* 在这里填写 *) Admitted.
☐
关于 while 命令,一个更有趣的事实是:循环体的任意多份副本 都可以被「展开」而不改变含义。
循环展开是任何真实编译器中的重要变换, 所以它的正确性不只有学术上的意义!
Theorem loop_unrolling : ∀ b c,
  cequiv
    <{ while b do c end }>
    <{ if b then c ; while b do c end else skip end }>.
Proof.
  (* 已在课上完成 *)
  intros b c st st'.
  split; intros Hce.
  - (* -> *)
    inversion Hce; subst.
    + (* 循环不执行 *)
      apply E_IfFalse.
      × assumption.
      × apply E_Skip.
    + (* 循环执行 *)
      apply E_IfTrue.
      × assumption.
      × apply E_Seq with (st' := st'0).
        -- assumption.
        -- assumption.
  - (* <- *)
    inversion Hce; subst.
    + (* 循环执行 *)
      inversion H5; subst.
      apply E_WhileTrue with (st' := st'0).
      × assumption.
      × assumption.
      × assumption.
    + (* 循环不执行 *)
      inversion H5; subst. apply E_WhileFalse. assumption. Qed.

练习: 2 stars,标准,可选 (seq_assoc)

Theorem seq_assoc : ∀ c1 c2 c3,
  cequiv <{(c1;c2);c3}> <{c1;(c2;c3)}>.
Proof.
  (* 在这里填写 *) Admitted.
☐
证明涉及赋值的程序性质时, 我们把程序状态之间的相等按外延方式处理 (例如 x !-> m x ; m 与 m 是相等的映射)。 这一事实常常派上用场。
Theorem identity_assignment : ∀ x,
  cequiv
    <{ x := x }>
    <{ skip }>.
Proof.
  intros.
  split; intro H; inversion H; subst; clear H.
  - (* -> *)
    rewrite t_update_same.
    apply E_Skip.
  - (* <- *)
    assert (Hx : st' =[ x := x ]=> (x !-> st' x ; st')).
    { apply E_Asgn. reflexivity. }
    rewrite t_update_same in Hx.
    apply Hx.
Qed.

练习: 2 stars,标准,特别有用 (assign_aequiv)

Theorem assign_aequiv : ∀ (X : string) (a : aexp),
  aequiv <{ X }> a →
  cequiv <{ skip }> <{ X := a }>.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 2 stars,标准,可选 (equiv_classes)

给定下列程序,把在 Imp 中等价的程序归为一组。 你的答案应给出为一个列表的列表,其中每个子列表表示一组 等价的程序。例如,若你认为程序 (a) 到 (h) 彼此等价、 但与 (i) 不等价,你的答案应形如:
       [ [prog_a;prog_b;prog_c;prog_d;prog_e;prog_f;prog_g;prog_h] ;
         [prog_i] ]
请在 equiv_classes 的定义中写下你的答案。
Definition prog_a : com :=
  <{ while X > 0 do
       X := X + 1
     end }>.

Definition prog_b : com :=
  <{ if (X = 0) then
       X := X + 1;
       Y := 1
     else
       Y := 0
     end;
     X := X - Y;
     Y := 0 }>.

Definition prog_c : com :=
  <{ skip }> .

Definition prog_d : com :=
  <{ while X ≠ 0 do
       X := (X × Y) + 1
     end }>.

Definition prog_e : com :=
  <{ Y := 0 }>.

Definition prog_f : com :=
  <{ Y := X + 1;
     while X ≠ Y do
       Y := X + 1
     end }>.

Definition prog_g : com :=
  <{ while true do
       skip
     end }>.

Definition prog_h : com :=
  <{ while X ≠ X do
       X := X + 1
     end }>.

Definition prog_i : com :=
  <{ while X ≠ Y do
       X := Y + 1
     end }>.

Definition equiv_classes : list (list com)
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

(* 不要修改下面这行: *)
Definition manual_grade_for_equiv_classes : option (nat×string) := None.
☐

行为等价的性质

接下来我们考虑程序等价的一些基本性质。

行为等价是一种等价关系

首先,我们来验证 aexps、bexps 和 com 上的等价确实是 【等价关系|Equivalence Relation】,即它们是自反、对称且传递的。 这些证明都很容易。
Lemma refl_aequiv : ∀ (a : aexp),
  aequiv a a.
Proof.
  intros a st. reflexivity. Qed.

Lemma sym_aequiv : ∀ (a1 a2 : aexp),
  aequiv a1 a2 → aequiv a2 a1.
Proof.
  intros a1 a2 H. intros st. symmetry. apply H. Qed.

Lemma trans_aequiv : ∀ (a1 a2 a3 : aexp),
  aequiv a1 a2 → aequiv a2 a3 → aequiv a1 a3.
Proof.
  unfold aequiv. intros a1 a2 a3 H12 H23 st.
  rewrite (H12 st). rewrite (H23 st). reflexivity. Qed.

Lemma refl_bequiv : ∀ (b : bexp),
  bequiv b b.
Proof.
  unfold bequiv. intros b st. reflexivity. Qed.

Lemma sym_bequiv : ∀ (b1 b2 : bexp),
  bequiv b1 b2 → bequiv b2 b1.
Proof.
  unfold bequiv. intros b1 b2 H. intros st. symmetry. apply H. Qed.

Lemma trans_bequiv : ∀ (b1 b2 b3 : bexp),
  bequiv b1 b2 → bequiv b2 b3 → bequiv b1 b3.
Proof.
  unfold bequiv. intros b1 b2 b3 H12 H23 st.
  rewrite (H12 st). rewrite (H23 st). reflexivity. Qed.

Lemma refl_cequiv : ∀ (c : com),
  cequiv c c.
Proof.
  unfold cequiv. intros c st st'. reflexivity. Qed.

Lemma sym_cequiv : ∀ (c1 c2 : com),
  cequiv c1 c2 → cequiv c2 c1.
Proof.
  unfold cequiv. intros c1 c2 H st st'.
  rewrite H. reflexivity.
Qed.

Lemma trans_cequiv : ∀ (c1 c2 c3 : com),
  cequiv c1 c2 → cequiv c2 c3 → cequiv c1 c3.
Proof.
  unfold cequiv. intros c1 c2 c3 H12 H23 st st'.
  rewrite H12. apply H23.
Qed.

行为等价是一个合同关系

不太明显的是,行为等价还是一个【合同|Congruence】。 也就是说,两个子程序等价蕴含它们所嵌入的更大程序等价:
aequiv a a'  

cequiv (x := a) (x := a')
cequiv c1 c1'
cequiv c2 c2'  

cequiv (c1;c2) (c1';c2')
……对其它形式的命令也一样。
(注意,这里使用推理规则记法, 并非把它作为归纳定义的一部分, 只是以可读形式写下一些成立的蕴含式。 下面将证明这些蕴含式。)
下一节(fold_constants_com_sound 的证明) 会给出一个具体示例,说明这些合同性质为何重要。 主要思想是:它们让我们可以把 大程序的一小部分替换成等价的一小部分。 且【无需】对未改变的部分做显式证明, 就能知道整个大程序等价。 换言之,对大程序的小改动, 「证明负担」与改动的大小成正比, 而与程序的大小无关!
Theorem CAsgn_congruence : ∀ x a a',
  aequiv a a' →
  cequiv <{x := a}> <{x := a'}>.
Proof.
  intros x a a' Heqv st st'.
  split; intros Hceval.
  - (* -> *)
    inversion Hceval. subst. apply E_Asgn.
    rewrite Heqv. reflexivity.
  - (* <- *)
    inversion Hceval. subst. apply E_Asgn.
    rewrite Heqv. reflexivity. Qed.
循环的合同性质更有趣,因为它需要归纳。
【定理】:等价对于 while 是一个合同;即,若 b 等价于 b' 且 c 等价于 c',则 while b do c end 等价于 while b' do c' end。
【证明】:假设 b 等价于 b' 且 c 等价于 c'。我们必须证明, 对每个 st 和 st',st =[ while b do c end ]=> st' 当且仅当 st =[ while b' do c' end ]=> st'。我们分别考虑两个方向。
  • (→) 我们对 st =[ while b do c end ]=> st' 的导出式归纳, 证明它蕴含 st =[ while b' do c' end ]=> st'。唯一不平凡的 情况是导出式的最后一条规则为 E_WhileFalse 或 E_WhileTrue。
    • E_WhileFalse:此时规则的形式给出 beval st b = false 和 st = st'。但由于 b 与 b' 等价,我们有 beval st b' = false,于是 E_WhileFalse 适用,推出 st =[ while b' do c' end ]=> st',即得所求。
    • E_WhileTrue:此时规则的形式给出 beval st b = true, 以及对某个状态 st'0 有 st =[ c ]=> st'0 和 st'0 =[ while b do c end ]=> st',还有归纳假设 st'0 =[ while b' do c' end ]=> st'。
      由于 c 与 c' 等价,我们知道 st =[ c' ]=> st'0; 又由于 b 与 b' 等价,我们有 beval st b' = true。 现在 E_WhileTrue 适用,推出 st =[ while b' do c' end ]=> st',即得所求。
  • (<-) 类似。☐
Theorem CWhile_congruence : ∀ b b' c c',
  bequiv b b' → cequiv c c' →
  cequiv <{ while b do c end }> <{ while b' do c' end }>.
Proof.
  (* 已在课上完成 *)

  (* 我们把一个方向放进 "assert" 中证明,
     以便在证明逆方向时复用。 *)

  assert (A: ∀ (b b' : bexp) (c c' : com) (st st' : state),
             bequiv b b' → cequiv c c' →
             st =[ while b do c end ]=> st' →
             st =[ while b' do c' end ]=> st').
  { unfold bequiv,cequiv.
    intros b b' c c' st st' Hbe Hc1e Hce.
    remember <{ while b do c end }> as cwhile
      eqn:Heqcwhile.
    induction Hce; inversion Heqcwhile; subst.
    + (* E_WhileFalse *)
      apply E_WhileFalse. rewrite <- Hbe. apply H.
    + (* E_WhileTrue *)
      apply E_WhileTrue with (st' := st').
      × (* 表明循环执行 *) rewrite <- Hbe. apply H.
      × (* 循环体的执行 *)
        apply (Hc1e st st'). apply Hce1.
      × (* 后续的循环执行 *)
        apply IHHce2. reflexivity. }

  intros. split.
  - apply A; assumption.
  - apply A.
    + apply sym_bequiv. assumption.
    + apply sym_cequiv. assumption.
Qed.

练习: 3 stars,标准,可选 (CSeq_congruence)

Theorem CSeq_congruence : ∀ c1 c1' c2 c2',
  cequiv c1 c1' → cequiv c2 c2' →
  cequiv <{ c1;c2 }> <{ c1';c2' }>.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (CIf_congruence)

Theorem CIf_congruence : ∀ b b' c1 c1' c2 c2',
  bequiv b b' → cequiv c1 c1' → cequiv c2 c2' →
  cequiv <{ if b then c1 else c2 end }>
         <{ if b' then c1' else c2' end }>.
Proof.
  (* 在这里填写 *) Admitted.
☐
例如,下面有两个程序,以及用这些合同定理证明它们等价的 过程……
Example congruence_example:
  cequiv
    (* 程序 1: *)
    <{ X := 0;
       if X = 0 then Y := 0
       else Y := 42 end }>
    (* 程序 2: *)
    <{ X := 0;
       if X = 0 then Y := X - X (* <--- 这里不同 *)
       else Y := 42 end }>.
Proof.
  apply CSeq_congruence.
  - apply refl_cequiv.
  - apply CIf_congruence.
    + apply refl_bequiv.
    + apply CAsgn_congruence. unfold aequiv. simpl.
      symmetry. apply sub_diag.
    + apply refl_cequiv.
Qed.

练习: 3 stars,高级 (not_congr)

我们已经证明 cequiv 关系在命令上 既是等价关系,也是合同关系。 你能想出一个在命令上的关系, 它是等价关系但【不是】合同关系吗? 请写下该关系(形式化的), 并附上它为等价关系的非形式化证明概要, 以及说明它不是合同关系的反例。
(* 在这里填写 *)
(* 不要修改下面这行: *)
Definition manual_grade_for_not_congr : option (nat×string) := None.
☐

程序变换

【程序变换|Program Transformation】是以程序为输入、产生修改后 程序作为输出的函数。【常量折叠|Constant Folding】等编译器优化 是典型的示例,当然还有许多别的示例。
若程序变换保持原程序的行为,则它是【可靠|Sound】的。
Definition atrans_sound (atrans : aexp → aexp) : Prop :=
  ∀ (a : aexp),
    aequiv a (atrans a).

Definition btrans_sound (btrans : bexp → bexp) : Prop :=
  ∀ (b : bexp),
    bequiv b (btrans b).

Definition ctrans_sound (ctrans : com → com) : Prop :=
  ∀ (c : com),
    cequiv c (ctrans c).

常量折叠变换

若表达式不含变量引用,则它是【常量|Constant】的。
常量折叠是一种找出常量表达式并将其替换为它们的值的优化。
Fixpoint fold_constants_aexp (a : aexp) : aexp :=
  match a with
  | ANum n ⇒ ANum n
  | AId x ⇒ AId x
  | <{ a1 + a2 }> ⇒
    match (fold_constants_aexp a1,
           fold_constants_aexp a2)
    with
    | (ANum n1, ANum n2) ⇒ ANum (n1 + n2)
    | (a1', a2') ⇒ <{ a1' + a2' }>
    end
  | <{ a1 - a2 }> ⇒
    match (fold_constants_aexp a1,
           fold_constants_aexp a2)
    with
    | (ANum n1, ANum n2) ⇒ ANum (n1 - n2)
    | (a1', a2') ⇒ <{ a1' - a2' }>
    end
  | <{ a1 × a2 }> ⇒
    match (fold_constants_aexp a1,
           fold_constants_aexp a2)
    with
    | (ANum n1, ANum n2) ⇒ ANum (n1 × n2)
    | (a1', a2') ⇒ <{ a1' × a2' }>
    end
  end.

Example fold_aexp_ex1 :
    fold_constants_aexp <{ (1 + 2) × X }>
  = <{ 3 × X }>.
Proof. reflexivity. Qed.
注意,这个版本的常量折叠 并不做其它「显而易见」的事情, 比如消去平凡的加法(例如把 0 + X 改写成 X)。 为简单起见,只聚焦于单个优化。
把其它简化表达式的方法加进来并不难,只是定义和证明会更长。 我们将在习题中考虑其中一些。
Example fold_aexp_ex2 :
  fold_constants_aexp <{ X - ((0 × 6) + Y) }> = <{ X - (0 + Y) }>.
Proof. reflexivity. Qed.
我们不仅可以把 fold_constants_aexp 提升到 bexp (在 BEq、BNeq 和 BLe 的情形下);还可以查找常量 【布尔|Boolean】表达式并就地求值。
Fixpoint fold_constants_bexp (b : bexp) : bexp :=
  match b with
  | <{true}> ⇒ <{true}>
  | <{false}> ⇒ <{false}>
  | <{ a1 = a2 }> ⇒
      match (fold_constants_aexp a1,
             fold_constants_aexp a2) with
      | (ANum n1, ANum n2) ⇒
          if n1 =? n2 then <{true}> else <{false}>
      | (a1', a2') ⇒
          <{ a1' = a2' }>
      end
  | <{ a1 ≠ a2 }> ⇒
      match (fold_constants_aexp a1,
             fold_constants_aexp a2) with
      | (ANum n1, ANum n2) ⇒
          if negb (n1 =? n2) then <{true}> else <{false}>
      | (a1', a2') ⇒
          <{ a1' ≠ a2' }>
      end
  | <{ a1 ≤ a2 }> ⇒
      match (fold_constants_aexp a1,
             fold_constants_aexp a2) with
      | (ANum n1, ANum n2) ⇒
          if n1 <=? n2 then <{true}> else <{false}>
      | (a1', a2') ⇒
          <{ a1' ≤ a2' }>
      end
  | <{ a1 > a2 }> ⇒
      match (fold_constants_aexp a1,
             fold_constants_aexp a2) with
      | (ANum n1, ANum n2) ⇒
          if n1 <=? n2 then <{false}> else <{true}>
      | (a1', a2') ⇒
          <{ a1' > a2' }>
      end
  | <{ ¬ b1 }> ⇒
      match (fold_constants_bexp b1) with
      | <{true}> ⇒ <{false}>
      | <{false}> ⇒ <{true}>
      | b1' ⇒ <{ ¬ b1' }>
      end
  | <{ b1 && b2 }> ⇒
      match (fold_constants_bexp b1,
             fold_constants_bexp b2) with
      | (<{true}>, <{true}>) ⇒ <{true}>
      | (<{true}>, <{false}>) ⇒ <{false}>
      | (<{false}>, <{true}>) ⇒ <{false}>
      | (<{false}>, <{false}>) ⇒ <{false}>
      | (b1', b2') ⇒ <{ b1' && b2' }>
      end
  end.

Example fold_bexp_ex1 :
  fold_constants_bexp <{ true && ¬(false && true) }>
  = <{ true }>.
Proof. reflexivity. Qed.

Example fold_bexp_ex2 :
  fold_constants_bexp <{ (X = Y) && (0 = (2 - (1 + 1))) }>
  = <{ (X = Y) && true }>.
Proof. reflexivity. Qed.
要折叠命令中的常量,我们只需对所有内嵌的表达式应用 相应的折叠函数。
Fixpoint fold_constants_com (c : com) : com :=
  match c with
  | <{ skip }> ⇒
      <{ skip }>
  | <{ x := a }> ⇒
      <{ x := (fold_constants_aexp a) }>
  | <{ c1 ; c2 }> ⇒
      <{ fold_constants_com c1 ; fold_constants_com c2 }>
  | <{ if b then c1 else c2 end }> ⇒
      match fold_constants_bexp b with
      | <{true}> ⇒ fold_constants_com c1
      | <{false}> ⇒ fold_constants_com c2
      | b' ⇒ <{ if b' then fold_constants_com c1
                       else fold_constants_com c2 end}>
      end
  | <{ while b do c1 end }> ⇒
      match fold_constants_bexp b with
      | <{true}> ⇒ <{ while true do skip end }>
      | <{false}> ⇒ <{ skip }>
      | b' ⇒ <{ while b' do (fold_constants_com c1) end }>
      end
  end.

Example fold_com_ex1 :
  fold_constants_com
    (* 原程序: *)
    <{ X := 4 + 5;
       Y := X - 3;
       if (X - Y) = (2 + 4) then skip
       else Y := 0 end;
       if 0 ≤ (4 - (2 + 1)) then Y := 0
       else skip end;
       while Y = 0 do
         X := X + 1
       end }>
  = (* 常量折叠后: *)
    <{ X := 9;
       Y := X - 3;
       if (X - Y) = 6 then skip
       else Y := 0 end;
       Y := 0;
       while Y = 0 do
         X := X + 1
       end }>.
Proof. reflexivity. Qed.

常量折叠的可靠性

现在我们需要表明所做的事情是正确的。
下面是对算术表达式的证明:
Theorem fold_constants_aexp_sound :
  atrans_sound fold_constants_aexp.
Proof.
  unfold atrans_sound. intros a. unfold aequiv. intros st.
  induction a; simpl;
    (* ANum 与 AId 立得 *)
    try reflexivity;
    (* APlus、AMinus 与 AMult 由归纳假设以及如下观察得出:
              aeval st (<{ a1 + a2 }>)
            = ANum ((aeval st a1) + (aeval st a2))
            = aeval st (ANum ((aeval st a1) + (aeval st a2)))
       (AMinus/minus 与 AMult/mult 同理) *)

    try (destruct (fold_constants_aexp a1);
         destruct (fold_constants_aexp a2);
         rewrite IHa1; rewrite IHa2; reflexivity). Qed.

练习: 3 stars,标准,可选 (fold_bexp_Eq_informal)

下面是布尔表达式常量折叠可靠性论证中 BEq 情形的非形式化证明。 请仔细阅读,并与随后的形式化证明作比较。然后补全形式化证明中的 BLe 情形(如果可能,不要看 BEq 情形)。
【定理】:布尔表达式的常量折叠函数 fold_constants_bexp 是可靠的。
【证明】:我们必须证明,对所有布尔表达式 b,b 等价于 fold_constants_bexp b。对 b 归纳。我们只给出 b 形如 a1 = a2 的情形。
在此情形下,我们必须证明
       beval st <{ a1 = a2 }>
     = beval st (fold_constants_bexp <{ a1 = a2 }>).
有两种情况需要考虑:
  • 首先,假设对某个 n1 和 n2 有 fold_constants_aexp a1 = ANum n1 和 fold_constants_aexp a2 = ANum n2。
    此时我们有
               fold_constants_bexp <{ a1 = a2 }>
             = if n1 =? n2 then <{true}> else <{false}>
    以及
               beval st <{a1 = a2}>
             = (aeval st a1) =? (aeval st a2).
    由算术表达式常量折叠的可靠性(引理 fold_constants_aexp_sound) 可知
               aeval st a1
             = aeval st (fold_constants_aexp a1)
             = aeval st (ANum n1)
             = n1
    以及
               aeval st a2
             = aeval st (fold_constants_aexp a2)
             = aeval st (ANum n2)
             = n2,
    于是
               beval st <{a1 = a2}>
             = (aeval a1) =? (aeval a2)
             = n1 =? n2.
    此外,分别考虑 n1 = n2 与 n1 ≠ n2 两种情形,容易看出
               beval st (if n1 =? n2 then <{true}> else <{false}>)
             = if n1 =? n2 then beval st <{true}> else beval st <{false}>
             = if n1 =? n2 then true else false
             = n1 =? n2.
    因此
               beval st (<{ a1 = a2 }>)
             = n1 =? n2.
             = beval st (if n1 =? n2 then <{true}> else <{false}>),
    即得所求。
  • 否则,fold_constants_aexp a1 与 fold_constants_aexp a2 之一不是常量。此时我们必须证明
               beval st <{a1 = a2}>
             = beval st (<{ (fold_constants_aexp a1) =
                             (fold_constants_aexp a2) }>),
    由 beval 的定义,这等同于证明
               (aeval st a1) =? (aeval st a2)
             = (aeval st (fold_constants_aexp a1)) =?
                       (aeval st (fold_constants_aexp a2)).
    而算术表达式常量折叠的可靠性(fold_constants_aexp_sound)给出
             aeval st a1 = aeval st (fold_constants_aexp a1)
             aeval st a2 = aeval st (fold_constants_aexp a2),
    本情形证毕。 ☐
Theorem fold_constants_bexp_sound:
  btrans_sound fold_constants_bexp.
Proof.
  unfold btrans_sound. intros b. unfold bequiv. intros st.
  induction b;
    (* true 与 false 立得 *)
    try reflexivity.
  - (* BEq *)
    simpl.
    remember (fold_constants_aexp a1) as a1' eqn:Heqa1'.
    remember (fold_constants_aexp a2) as a2' eqn:Heqa2'.
    replace (aeval st a1) with (aeval st a1') by
       (subst a1'; rewrite <- fold_constants_aexp_sound; reflexivity).
    replace (aeval st a2) with (aeval st a2') by
       (subst a2'; rewrite <- fold_constants_aexp_sound; reflexivity).
    destruct a1'; destruct a2'; try reflexivity.
    (* 唯一有趣的情形是 a1 与 a2 折叠后都变为常量 *)
      simpl. destruct (n =? n0); reflexivity.
  - (* BNeq *)
    simpl.
    remember (fold_constants_aexp a1) as a1' eqn:Heqa1'.
    remember (fold_constants_aexp a2) as a2' eqn:Heqa2'.
    replace (aeval st a1) with (aeval st a1') by
       (subst a1'; rewrite <- fold_constants_aexp_sound; reflexivity).
    replace (aeval st a2) with (aeval st a2') by
       (subst a2'; rewrite <- fold_constants_aexp_sound; reflexivity).
    destruct a1'; destruct a2'; try reflexivity.
    (* 唯一有趣的情形是 a1 与 a2 折叠后都变为常量 *)
      simpl. destruct (n =? n0); reflexivity.
  - (* BLe *)
    (* 在这里填写 *) admit.
  - (* BGt *)
    (* 在这里填写 *) admit.
  - (* BNot *)
    simpl. remember (fold_constants_bexp b) as b' eqn:Heqb'.
    rewrite IHb.
    destruct b'; reflexivity.
  - (* BAnd *)
    simpl.
    remember (fold_constants_bexp b1) as b1' eqn:Heqb1'.
    remember (fold_constants_bexp b2) as b2' eqn:Heqb2'.
    rewrite IHb1. rewrite IHb2.
    destruct b1'; destruct b2'; reflexivity.
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (fold_constants_com_sound)

补全下列证明的 while 情形。
Theorem fold_constants_com_sound :
  ctrans_sound fold_constants_com.
Proof.
  unfold ctrans_sound. intros c.
  induction c; simpl.
  - (* skip *) apply refl_cequiv.
  - (* := *) apply CAsgn_congruence.
              apply fold_constants_aexp_sound.
  - (* ; *) apply CSeq_congruence; assumption.
  - (* if *)
    assert (bequiv b (fold_constants_bexp b)). {
      apply fold_constants_bexp_sound. }
    destruct (fold_constants_bexp b) eqn:Heqb;
      try (apply CIf_congruence; assumption).
      (* (若优化没有消去该 if,则由归纳假设和
          fold_constants_bexp_sound 容易证明结果。) *)

    + (* b 恒为 true *)
      apply trans_cequiv with c1; try assumption.
      apply if_true; assumption.
    + (* b 恒为 false *)
      apply trans_cequiv with c2; try assumption.
      apply if_false; assumption.
  - (* while *)
    (* 在这里填写 *) Admitted.
☐

再论 (0 + n) 消除的可靠性

练习: 4 stars,标准,可选 (optimize_0plus_var)

回顾【《逻辑基础》】Imp 一章中 optimize_0plus 的定义:
    Fixpoint optimize_0plus (a:aexp) : aexp :=
      match a with
      | ANum n ⇒
          ANum n
      | <{ 0 + a2 }> ⇒
          optimize_0plus a2
      | <{ a1 + a2 }> ⇒
          <{ (optimize_0plus a1) + (optimize_0plus a2) }>
      | <{ a1 - a2 }> ⇒
          <{ (optimize_0plus a1) - (optimize_0plus a2) }>
      | <{ a1 × a2 }> ⇒
          <{ (optimize_0plus a1) × (optimize_0plus a2) }>
      end.
注意,该函数是针对没有状态的旧版 aexp 定义的。
请写出该函数的新版本,使其能处理变量(即保持变量原样), 并为 bexp 和命令写出类似的函数:
     optimize_0plus_aexp
     optimize_0plus_bexp
     optimize_0plus_com
Fixpoint optimize_0plus_aexp (a : aexp) : aexp
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Fixpoint optimize_0plus_bexp (b : bexp) : bexp
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Fixpoint optimize_0plus_com (c : com) : com
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Example test_optimize_0plus:
    optimize_0plus_com
       <{ while X ≠ 0 do X := 0 + X - 1 end }>
  = <{ while X ≠ 0 do X := X - 1 end }>.
Proof.
  (* 在这里填写 *) Admitted.
证明这三个函数是可靠的,正如我们对 fold_constants_× 做过的 那样。在 optimize_0plus_com 的证明中请务必使用合同引理, 否则证明会很【长】!
Theorem optimize_0plus_aexp_sound:
  atrans_sound optimize_0plus_aexp.
Proof.
  (* 在这里填写 *) Admitted.

Theorem optimize_0plus_bexp_sound :
  btrans_sound optimize_0plus_bexp.
Proof.
  (* 在这里填写 *) Admitted.

Theorem optimize_0plus_com_sound :
  ctrans_sound optimize_0plus_com.
Proof.
  (* 在这里填写 *) Admitted.
最后,我们来定义一个命令上的复合优化器:它先折叠常量 (用 fold_constants_com),再消去 0 + n 项 (用 optimize_0plus_com)。
证明该优化器是可靠的。
Theorem optimizer_sound :
  ctrans_sound optimizer.
Proof.
  (* 在这里填写 *) Admitted.
☐

证明不等价

接下来,我们看一些【不】等价的程序。
假设 c1 是形如
       X := a1; Y := a2 的命令,而 c2 是命令
       X := a1; Y := a2' 其中 a2' 由把 a2 中 X 的每次出现替换为 a1 而形成。
例如,c1 和 c2 可以是:
       c1 = (X := 42 + 53;
               Y := Y + X)
       c2 = (X := 42 + 53;
               Y := Y + (42 + 53))
显然,这个【特定的】 c1 与 c2 是等价的。一般而言也如此吗?
我们马上就会看到答案是否定的,不过现在不妨停下来, 看看你能否自己找出一个反例。
更形式化地,下面是把算术表达式 u 替换为另一表达式 a 中 给定变量 x 的每次出现的函数:
Fixpoint subst_aexp (x : string) (u : aexp) (a : aexp) : aexp :=
  match a with
  | ANum n ⇒
      ANum n
  | AId x' ⇒
      if String.eqb x x' then u else AId x'
  | <{ a1 + a2 }> ⇒
      <{ (subst_aexp x u a1) + (subst_aexp x u a2) }>
  | <{ a1 - a2 }> ⇒
      <{ (subst_aexp x u a1) - (subst_aexp x u a2) }>
  | <{ a1 × a2 }> ⇒
      <{ (subst_aexp x u a1) × (subst_aexp x u a2) }>
  end.

Example subst_aexp_ex :
  subst_aexp X <{42 + 53}> <{Y + X}>
  = <{ Y + (42 + 53)}>.
Proof. simpl. reflexivity. Qed.
而这里是我们感兴趣的性质,它表达如下论断:如上所述的命令 c1 与 c2 总是等价。
Definition subst_equiv_property : Prop := ∀ x1 x2 a1 a2,
  cequiv <{ x1 := a1; x2 := a2 }>
         <{ x1 := a1; x2 := subst_aexp x1 a1 a2 }>.
遗憾的是,该性质【并不】总是成立。
这里有一个反例:
       X := X + 1; Y := X 若执行替换,我们得到
       X := X + 1; Y := X + 1 显然二者不等价。
Theorem subst_inequiv :
  ¬ subst_equiv_property.
Proof.
  unfold subst_equiv_property.
  intros Contra.

  (* 这里是反例:假设 subst_equiv_property 成立
     让我们能够证明这两个程序等价…… *)

  remember <{ X := X + 1;
              Y := X }>
      as c1.
  remember <{ X := X + 1;
              Y := X + 1 }>
      as c2.
  assert (cequiv c1 c2) by (subst; apply Contra).
  clear Contra.

  (* ……让我们能够表明命令 c2 可以在两个不同的最终状态下终止:
         st1 = (Y !-> 1 ; X !-> 1)
         st2 = (Y !-> 2 ; X !-> 1). *)

  remember (Y !-> 1 ; X !-> 1) as st1.
  remember (Y !-> 2 ; X !-> 1) as st2.
  assert (H1 : empty_st =[ c1 ]=> st1);
  assert (H2 : empty_st =[ c2 ]=> st2);
  try (subst;
       apply E_Seq with (st' := (X !-> 1));
       apply E_Asgn; reflexivity).
  clear Heqc1 Heqc2.

  apply H in H1.
  clear H.

  (* 最后,我们利用求值是确定性的这一事实得出矛盾。 *)
  assert (Hcontra : st1 = st2)
    by (apply (ceval_deterministic c2 empty_st); assumption).
  clear H1 H2.

  assert (Hcontra' : st1 Y = st2 Y)
    by (rewrite Hcontra; reflexivity).
  subst. discriminate. Qed.

练习: 4 stars,标准,可选 (better_subst_equiv)

我们上面想到的等价并非完全是无稽之谈,事实上它几乎是对的。 要使它正确,我们只需排除变量 X 出现在第一条赋值语句 右边的情形。
Inductive var_not_used_in_aexp (x : string) : aexp → Prop :=
  | VNUNum : ∀ n, var_not_used_in_aexp x (ANum n)
  | VNUId : ∀ y, x ≠ y → var_not_used_in_aexp x (AId y)
  | VNUPlus : ∀ a1 a2,
      var_not_used_in_aexp x a1 →
      var_not_used_in_aexp x a2 →
      var_not_used_in_aexp x (<{ a1 + a2 }>)
  | VNUMinus : ∀ a1 a2,
      var_not_used_in_aexp x a1 →
      var_not_used_in_aexp x a2 →
      var_not_used_in_aexp x (<{ a1 - a2 }>)
  | VNUMult : ∀ a1 a2,
      var_not_used_in_aexp x a1 →
      var_not_used_in_aexp x a2 →
      var_not_used_in_aexp x (<{ a1 × a2 }>).

Lemma aeval_weakening : ∀ x st a ni,
  var_not_used_in_aexp x a →
  aeval (x !-> ni ; st) a = aeval st a.
Proof.
  (* 在这里填写 *) Admitted.
用 var_not_used_in_aexp 形式化并证明 subst_equiv_property 的正确版本。
(* 在这里填写 *)
☐

练习: 3 stars,标准 (inequiv_exercise)

证明无限循环不等价于 skip
Theorem inequiv_exercise:
  ¬ cequiv <{ while true do skip end }> <{ skip }>.
Proof.
  (* 在这里填写 *) Admitted.
☐

扩展练习:非确定性 Imp

正如我们已经看到的(Imp 一章中的定理 ceval_deterministic), Imp 的求值关系是确定性的。然而,【非】确定性是许多真实编程语言 定义的重要组成部分。例如,在许多指令式语言(如 C 及其亲属) 中,函数参数的求值顺序是未指定的:程序片段
      x = 0;
      f(++x, x)
可能以参数 (1, 0) 或 (1, 1) 调用 f,取决于编译器如何选择 顺序。这可能让程序员有点困惑,但它给了编译器作者有用的自由。
在本练习中,我们将用一条简单的非确定性命令扩展 Imp, 并研究这一改变如何影响程序等价。新命令的语法是 HAVOC X, 其中 X 是标识符。执行 HAVOC X 的效果是【任意】地、非确定性地 为变量 X 赋一个数。例如,执行完程序
      HAVOC Y;
      Z := Y × 2
后,Y 可以是任何数,而 Z 是 Y 的两倍(因此 Z 总是偶数)。 注意,这里说的不是结果的【概率】。 只是说执行这段非确定性代码之后, 可能产生(无穷多)种不同的结果。
某种意义上,我们对其做 HAVOC 的变量大致对应于 C 这类低级语言 中的未初始化变量。HAVOC 之后,该变量保存一个固定但任意的数。 语言定义中的大多数非确定性之所以存在, 是因为程序员并不在乎作出哪种选择。 所以让编译器去选择运行更快的那种是好事。
我们称这个新语言为Himp(「用 HAVOC 扩展的 Imp」)。
Module Himp.
为了形式化 Himp,我们首先在命令的定义中增加一条子句。
Inductive com : Type :=
  | CSkip : com
  | CAsgn : string → aexp → com
  | CSeq : com → com → com
  | CIf : bexp → com → com → com
  | CWhile : bexp → com → com
  | CHavoc : string → com. (* <--- 新增 *)

Notation "'havoc' l" := (CHavoc l)
                          (in custom com at level 60, l constr at level 0).
Notation "'skip'" := CSkip
  (in custom com at level 0) : com_scope.
Notation "x := y" := (CAsgn x y)
  (in custom com at level 0, x constr at level 0, y at level 85, no associativity,
    format "x := y") : com_scope.
Notation "x ; y" := (CSeq x y)
  (in custom com at level 90,
    right associativity,
    format "'[v' x ; '/' y ']'") : com_scope.
Notation "'if' x 'then' y 'else' z 'end'" := (CIf x y z)
  (in custom com at level 89, x at level 99, y at level 99, z at level 99,
    format "'[v' 'if' x 'then' '/ ' y '/' 'else' '/ ' z '/' 'end' ']'") : com_scope.
Notation "'while' x 'do' y 'end'" := (CWhile x y)
  (in custom com at level 89, x at level 99, y at level 99,
    format "'[v' 'while' x 'do' '/ ' y '/' 'end' ']'") : com_scope.

练习: 2 stars,标准 (himp_ceval)

现在,我们必须扩展操作语义。下面给出了 ceval 关系的模板, 指定了大步语义。为了形式化 HAVOC 命令的行为,需要在 ceval 的定义中添加什么规则?

Inductive ceval : com → state → state → Prop :=
  | E_Skip : ∀ st,
      st =[ skip ]=> st
  | E_Asgn : ∀ st a n x,
      aeval st a = n →
      st =[ x := a ]=> (x !-> n ; st)
  | E_Seq : ∀ c1 c2 st st' st'',
      st =[ c1 ]=> st' →
      st' =[ c2 ]=> st'' →
      st =[ c1 ; c2 ]=> st''
  | E_IfTrue : ∀ st st' b c1 c2,
      beval st b = true →
      st =[ c1 ]=> st' →
      st =[ if b then c1 else c2 end ]=> st'
  | E_IfFalse : ∀ st st' b c1 c2,
      beval st b = false →
      st =[ c2 ]=> st' →
      st =[ if b then c1 else c2 end ]=> st'
  | E_WhileFalse : ∀ b st c,
      beval st b = false →
      st =[ while b do c end ]=> st
  | E_WhileTrue : ∀ st st' st'' b c,
      beval st b = true →
      st =[ c ]=> st' →
      st' =[ while b do c end ]=> st'' →
      st =[ while b do c end ]=> st''
(* 在这里填写 *)

  where "st =[ c ]=> st'" := (ceval c st st').
作为合理性检查,以下论断对你的定义来说应当是可证的:
Example havoc_example1 : empty_st =[ havoc X ]=> (X !-> 0).
Proof.
(* 在这里填写 *) Admitted.

Example havoc_example2 :
  empty_st =[ skip; havoc Z ]=> (Z !-> 42).
Proof.
(* 在这里填写 *) Admitted.

(* 不要修改下面这行: *)
Definition manual_grade_for_Check_rule_for_HAVOC : option (nat×string) := None.
☐
最后,我们重复上面的命令等价定义:
Definition cequiv (c1 c2 : com) : Prop := ∀ st st' : state,
  st =[ c1 ]=> st' ↔ st =[ c2 ]=> st'.
让我们应用这个定义来证明一些非确定性程序等价或不等价。

练习: 3 stars,标准 (havoc_swap)

下列两个程序等价吗?
Definition pXY :=
  <{ havoc X ; havoc Y }>.

Definition pYX :=
  <{ havoc Y; havoc X }>.
若你认为它们等价,请证明;若认为不等价,也请证明。
Theorem pXY_cequiv_pYX :
  cequiv pXY pYX ∨ ¬cequiv pXY pYX.
Proof.
  (* 提示:你可能在某处想用 t_update_permute,那样多半会剩下
     X ≠ Y 作为假设。你可以用 discriminate 消除它。 *)

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

练习: 4 stars,标准,可选 (havoc_copy)

下列两个程序等价吗?
Definition ptwice :=
  <{ havoc X; havoc Y }>.

Definition pcopy :=
  <{ havoc X; Y := X }>.
若你认为它们等价,请证明;若认为不等价,也请证明。 (提示:你可能会发现 assert 策略有用。)
Theorem ptwice_cequiv_pcopy :
  cequiv ptwice pcopy ∨ ¬cequiv ptwice pcopy.
Proof. (* 在这里填写 *) Admitted.
☐
这里使用的程序等价定义, 对可能永远循环的程序有一些微妙推论。 cequiv 说的是:两个等价程序 可能的【终止】结果集合相同。 但在 Himp 这样带非确定性的语言中, 有些程序总是终止,有些总是发散。 还有些可能非确定地在某些运行中终止、 在另一些运行中发散。 下面练习的最后一部分说明了这一现象。

练习: 4 stars,高级 (p1_p2_term)

考虑下列命令:
Definition p1 : com :=
  <{ while ¬ (X = 0) do
       havoc Y;
       X := X + 1
     end }>.

Definition p2 : com :=
  <{ while ¬ (X = 0) do
       skip
     end }>.
直觉上,p1 与 p2 有相同的终止行为:要么永远循环, 要么终止于与起始时相同的状态。我们可以用以下引理 分别刻画 p1 与 p2 的终止行为:
Lemma p1_may_diverge : ∀ st st', st X ≠ 0 →
  ¬ st =[ p1 ]=> st'.
Proof. (* 在这里填写 *) Admitted.

Lemma p2_may_diverge : ∀ st st', st X ≠ 0 →
  ¬ st =[ p2 ]=> st'.
Proof.
(* 在这里填写 *) Admitted.
☐

练习: 4 stars,高级 (p1_p2_equiv)

用这两条引理证明 p1 与 p2 实际上等价。
Theorem p1_p2_equiv : cequiv p1 p2.
Proof. (* 在这里填写 *) Admitted.
☐

练习: 4 stars,高级 (p3_p4_inequiv)

证明下列程序【不】等价。(提示:p3 终止时 Z 的值应是什么? p4 呢?)
Definition p3 : com :=
  <{ Z := 1;
     while X ≠ 0 do
       havoc X;
       havoc Z
     end }>.

Definition p4 : com :=
  <{ X := 0;
     Z := 1 }>.

Theorem p3_p4_inequiv : ¬ cequiv p3 p4.
Proof. (* 在这里填写 *) Admitted.
☐

练习: 5 stars,高级,可选 (p5_p6_equiv)

证明下列命令等价。 (提示:如上所述,我们为 Himp 定义的 cequiv 只考虑可能的终止配置集合。 两个程序等价,当且仅当在相同起始状态 st 下, 二者可能的终止状态集合相同。 若 p5 终止,最终状态应当是什么? 反过来,是否总能让 p5 终止?)
Definition p5 : com :=
  <{ while X ≠ 1 do
       havoc X
     end }>.

Definition p6 : com :=
  <{ X := 1 }>.

Theorem p5_p6_equiv : cequiv p5 p6.
Proof. (* 在这里填写 *) Admitted.
☐
End Himp.

附加练习

练习: 3 stars,标准,可选 (swap_noninterfering_assignments)

(提示:这道题可能需要、也可能不需要显式使用 functional_extensionality,取决于你如何入手。)
Theorem swap_noninterfering_assignments: ∀ l1 l2 a1 a2,
  l1 ≠ l2 →
  var_not_used_in_aexp l1 a2 →
  var_not_used_in_aexp l2 a1 →
  cequiv
    <{ l1 := a1; l2 := a2 }>
    <{ l2 := a2; l1 := a1 }>.
Proof.
(* 在这里填写 *) Admitted.
☐

练习: 4 stars,标准,可选 (for_while_equiv)

本练习扩展了 Imp 一章中可选的 add_for_loop 练习,在那里你被要求用 C 风格的 for 循环扩展命令语言。 请证明命令:
      for (c1; b; c2) {
          c3
      }
等价于:
       c1;
       while b do
         c3;
         c2
       end
(* 在这里填写 *)
☐

练习: 4 stars,高级,可选 (capprox)

在本练习中,我们定义程序等价的一个非对称变体, 称为【程序近似|Program Approximation】。我们说程序 c1 【近似于】程序 c2,是指对每个使 c1 终止的初始状态, c2 也终止并产生相同的最终状态。形式化地, 程序近似定义如下:
Definition capprox (c1 c2 : com) : Prop := ∀ (st st' : state),
  st =[ c1 ]=> st' → st =[ c2 ]=> st'.
例如,程序
  c1 = while X ≠ 1 do
         X := X - 1
       end
近似于 c2 = X := 1,但 c2 不近似于 c1, 因为 c1 在 X = 0 时不终止而 c2 终止。 若两个程序在两个方向上互相近似,则它们等价。
找出两个程序 c3 和 c4,使得它们互不近似。
Definition c3 : com
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.
Definition c4 : com
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Theorem c3_c4_different : ¬ capprox c3 c4 ∧ ¬ capprox c4 c3.
Proof. (* 在这里填写 *) Admitted.
找出一个近似于所有其它程序的程序 cmin。
Definition cmin : com
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Theorem cmin_minimal : ∀ c, capprox cmin c.
Proof. (* 在这里填写 *) Admitted.
最后,找出一个被程序近似保持(从左到右时)的非平凡性质。
Definition zprop (c : com) : Prop
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Theorem zprop_preserving : ∀ c c',
  zprop c → capprox c c' → zprop c'.
Proof. (* 在这里填写 *) Admitted.
☐
(* 2026-11-26 15:55 *)