Imp简单的指令式程序

在本章中,我们会更认真地看待如何用 Rocq 作为工具来研究其他东西。 我们的案例研究是一个名为 Imp 的简单【指令式|Imperative】编程语言。 它体现了 C 和 Java 等传统主流语言的一小段核心片段。
下面是一个用 Imp 写的常见数学函数。
       Z := X;
       Y := 1;
       while Z ≠ 0 do
         Y := Y × Z;
         Z := Z - 1
       end
我们在此集中定义 Imp 的【语法|Syntax】和【语义|Semantics】。 以后在《编程语言基础》(《Software Foundations》第 2 卷)中, 我们会发展【程序等价|Program Equivalence】理论,并引入【霍尔逻辑|Hoare Logic】。 它是推理指令式程序的一种流行逻辑。
Set Warnings "-notation-overridden".
From Stdlib Require Import Bool.
From Stdlib Require Import Init.Nat.
From Stdlib Require Import Arith.
From Stdlib Require Import EqNat. Import Nat.
From Stdlib Require Import Lia.
From Stdlib Require Import List. Import ListNotations.
From Stdlib Require Import Strings.String.
From LF Require Import Maps.

算术与布尔表达式

我们将分三部分介绍 Imp。 首先是【算术与布尔表达式】的核心语言。 然后用【变量】扩展这些表达式。 最后是包含赋值、条件、顺序组合与循环的【命令】语言。

语法

Module AExp.
这两个定义指定了算术与布尔表达式的【抽象语法|Abstract Syntax】。
Inductive aexp : Type :=
  | ANum (n : nat)
  | APlus (a1 a2 : aexp)
  | AMinus (a1 a2 : aexp)
  | AMult (a1 a2 : aexp).

Inductive bexp : Type :=
  | BTrue
  | BFalse
  | BEq (a1 a2 : aexp)
  | BNeq (a1 a2 : aexp)
  | BLe (a1 a2 : aexp)
  | BGt (a1 a2 : aexp)
  | BNot (b : bexp)
  | BAnd (b1 b2 : bexp).
在本章中,我们会基本略去从程序员实际书写的【具体语法|Concrete Syntax】 到这些抽象语法树的翻译过程。 例如,把字符串 "1 + 2 × 3" 翻译成 AST
      APlus (ANum 1) (AMult (ANum 2) (ANum 3)). 可选章节 ImpParser 开发了一个能完成这种翻译的简单词法分析器 与解析器。理解本章并不需要那一章。 但若你还没上过涵盖这些技术的课程(例如编译器课程), 可能值得略读一下。
作为对比,下面是用传统 BNF(Backus-Naur Form,巴克斯-诺尔范式) 文法定义同一抽象语法:
    a := nat
        | a + a
        | a - a
        | a × a

    b := true
        | false
        | a = a
        | a ≠ a
        | a ≤ a
        | a > a
        | ¬b
        | b && b
与上面的 Rocq 版本相比……
  • BNF 更非形式化。例如,它给出表达式表面语法的一些建议 (例如加法运算写作中缀 +)。 词法分析与解析的其他方面则留作未指定, 如 +/-/× 的相对优先级、用括号分组子表达式等。 要把这描述变成形式化定义(例如实现编译器), 还需要一些额外信息,以及人类的智慧。
    Rocq 版本则一贯省略所有这些信息,只专注于抽象语法。
  • 反过来,BNF 版本更轻、更易读。它的非形式化使之灵活, 这在黑板讨论等场合是很大优势:此时传达一般想法, 比精确钉死每个细节更重要。
    确实,存在几十种类似 BNF 的记法,人们在其中随意切换。 通常甚至不说是哪一种 BNF,因为没必要。 大致的非形式化理解才要紧。
对两种记法都感到顺手是好的:非形式化的用于人与人之间的交流, 形式的用于实施实现与证明。

求值

对算术表达式【求值|Evaluation】会得到一个数。
Fixpoint aeval (a : aexp) : nat :=
  match a with
  | ANum n ⇒ n
  | APlus a1 a2 ⇒ (aeval a1) + (aeval a2)
  | AMinus a1 a2 ⇒ (aeval a1) - (aeval a2)
  | AMult a1 a2 ⇒ (aeval a1) × (aeval a2)
  end.

Example test_aeval1:
  aeval (APlus (ANum 2) (ANum 2)) = 4.
Proof. reflexivity. Qed.
类似地,对布尔表达式求值会得到一个布尔值。
Fixpoint beval (b : bexp) : bool :=
  match b with
  | BTrue ⇒ true
  | BFalse ⇒ false
  | BEq a1 a2 ⇒ (aeval a1) =? (aeval a2)
  | BNeq a1 a2 ⇒ negb ((aeval a1) =? (aeval a2))
  | BLe a1 a2 ⇒ (aeval a1) <=? (aeval a2)
  | BGt a1 a2 ⇒ negb ((aeval a1) <=? (aeval a2))
  | BNot b1 ⇒ negb (beval b1)
  | BAnd b1 b2 ⇒ andb (beval b1) (beval b2)
  end.

优化

我们还没定义太多东西,但已经能从这些定义中得到一些用处了。 假设我们定义一个函数:它接收算术表达式并稍作化简, 把每一处 0 + e(即 (APlus (ANum 0) e)改成仅 e。
Fixpoint optimize_0plus (a:aexp) : aexp :=
  match a with
  | ANum n ⇒ ANum n
  | APlus (ANum 0) e2 ⇒ optimize_0plus e2
  | APlus e1 e2 ⇒ APlus (optimize_0plus e1) (optimize_0plus e2)
  | AMinus e1 e2 ⇒ AMinus (optimize_0plus e1) (optimize_0plus e2)
  | AMult e1 e2 ⇒ AMult (optimize_0plus e1) (optimize_0plus e2)
  end.
为了确信优化做对了,可以在一些示例上测试, 看看输出是否正常。
Example test_optimize_0plus:
  optimize_0plus (APlus (ANum 2)
                        (APlus (ANum 0)
                               (APlus (ANum 0) (ANum 1))))
  = APlus (ANum 2) (ANum 1).
Proof. reflexivity. Qed.
但若要确信优化是正确的,就应当证明它: 对优化后的表达式求值,【总是】给出与原表达式相同的结果。
Theorem optimize_0plus_sound: ∀ a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a. induction a.
  - (* ANum *) reflexivity.
  - (* APlus *) destruct a1 eqn:Ea1.
    + (* a1 = ANum n *) destruct n eqn:En.
      × (* n = 0 *) simpl. apply IHa2.
      × (* n <> 0 *) simpl. rewrite IHa2. reflexivity.
    + (* a1 = APlus a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
    + (* a1 = AMinus a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
    + (* a1 = AMult a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
  - (* AMinus *)
    simpl. rewrite IHa1. rewrite IHa2. reflexivity.
  - (* AMult *)
    simpl. rewrite IHa1. rewrite IHa2. reflexivity. Qed.

Rocq 自动化

上一个证明中的重复有点烦人。 而且,无论语言还是正在证明的性质,只要明显更复杂, 就会开始成为真正的问题。
迄今为止,我们只用了 Rocq 的一小撮策略做全部证明。 完全忽略了它自动构造证明片段的强大设施。 本节介绍其中一些设施,后面几章还会看到更多。 习惯它们要花些力气:Rocq 的自动化是强力工具。 它能让我们把精力扩展到更复杂的定义与更有趣的性质上, 而不被无聊、重复、底层的细节淹没。

泛策略

【泛策略|Tacticals】是 Rocq 对「以其他策略为参数的策略」的称呼。 也可以说是「高阶策略」。

try 泛策略

若 T 是一个策略,则 try T 与 T 几乎相同。 只是当 T 失败时,try T 会【成功地】什么都不做(而非失败)。
Theorem silly1 : ∀ (P : Prop), P → P.
Proof.
  intros P HP.
  try reflexivity. (* 普通的 reflexivity 会失败。 *)
  apply HP. (* 我们仍可用别的方式完成证明。 *)
Qed.

Theorem silly2 : ∀ ae, aeval ae = aeval ae.
Proof.
    try reflexivity. (* 这就只是做了 reflexivity。 *)
Qed.
在这类完全手工的证明中,没有多少理由使用 try。 但与下面要展示的 ; 泛策略一起做自动化证明时,它非常有用。

; 泛策略(简单形式)

在最常见的形式中,; 泛策略接受两个策略作参数。复合策略 T;T' 先执行 T,再在 T 生成的【每个子目标】上执行 T'。
例如,考虑下列平凡引理:
Lemma foo : ∀ n, 0 <=? n = true.
Proof.
  intros.
  destruct n.
    (* 留下两个子目标,它们的处理方式相同…… *)
    - (* n=0 *) simpl. reflexivity.
    - (* n=Sn' *) simpl. reflexivity.
Qed.
我们可以用 ; 泛策略化简这个证明:
Lemma foo' : ∀ n, 0 <=? n = true.
Proof.
  intros.
  (* destruct 解构当前目标 *)
  destruct n;
  (* 然后对每个得到的子目标做 simpl *)
  simpl;
  (* 并对每个得到的子目标做 reflexivity *)
  reflexivity.
Qed.
把 try 与 ; 一起用,就能去掉刚才那个证明里让人烦的重复。
Theorem optimize_0plus_sound': ∀ a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a.
  induction a;
    (* 多数情形可由归纳假设直接得到…… *)
    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).
    (* ……但剩下的情形 ANum 与 APlus 则不同: *)
  - (* ANum *) reflexivity.
  - (* APlus *)
    destruct a1 eqn:Ea1;
      (* 同样,多数情形可由归纳假设直接得到: *)
      try (simpl; simpl in IHa1; rewrite IHa1;
           rewrite IHa2; reflexivity).
    (* 有趣的情形是 e1 = ANum n,此时 try... 什么也不做。
       我们必须对 n 做解构(看优化是否适用),并用归纳假设改写。 *)

    + (* a1 = ANum n *) destruct n eqn:En;
      simpl; rewrite IHa2; reflexivity. Qed.
Rocq 专家常在 induction 这类策略之后使用「...; try... 」习语, 一次处理许多相似情形。这种做法在非形式化证明中也有对应。 例如,下面是对优化定理的非形式化证明,其结构与形式化证明一致:
【定理】:对所有算术表达式 a,
       aeval (optimize_0plus a) = aeval a. 【证明】:对 a 归纳。多数情形由归纳假设直接得到。其余情形如下:
  • 假设对某个 n 有 a = ANum n。我们必须表明
              aeval (optimize_0plus (ANum n)) = aeval (ANum n). 这由 optimize_0plus 的定义立即得出。
  • 假设对某个 a1 与 a2 有 a = APlus a1 a2。我们必须表明
              aeval (optimize_0plus (APlus a1 a2)) = aeval (APlus a1 a2). 考虑 a1 可能的形式。对多数形式,optimize_0plus 只是 对子表达式递归调用自身,并重建与 a1 同形的新表达式; 这些情形的结果由归纳假设直接得到。
    有趣的情形是对某个 n 有 a1 = ANum n。若 n = 0,则
              optimize_0plus (APlus a1 a2) = optimize_0plus a2 而 a2 的归纳假设正是我们所需。另一方面,若对某个 n' 有 n = S n',则同样 optimize_0plus 只是递归调用自身, 结果由归纳假设得到。☐
不过,这个证明仍可改进。 第一种情形(a = ANum n)非常平凡, 甚至比我们说由归纳假设直接得到的情形更平凡,却仍被完整写出。 更好也更清楚的做法是去掉它,只在开头说: 「多数情形或立即可得,或直接由归纳假设得到。 唯一有趣的情形是 APlus……」 我们的形式化证明也能同样改进。看起来像这样:
Theorem optimize_0plus_sound'': ∀ a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a.
  induction a;
    (* 多数情形由归纳假设直接得到 *)
    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
    (* ……或由定义立即可得 *)
    try reflexivity.
  (* 有趣的情形是 a = APlus a1 a2。 *)
  - (* APlus *)
    destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;
                      rewrite IHa2; reflexivity).
    + (* a1 = ANum n *) destruct n;
      simpl; rewrite IHa2; reflexivity. Qed.

; 泛策略(一般形式)

; 泛策略还有一种比上面所见简单形式 T;T' 更一般的形态。 若 T、T1、……、Tn 都是策略,则
      T; [T1 | T2 | ... | Tn] 先执行 T,再在 T 生成的第一个子目标上执行 T1, 在第二个子目标上执行 T2,依此类推。
因此 T;T' 只是所有 Ti 都相同时的特殊记法;即 T;T' 是:
      T; [T' | T' | ... | T'] 的简写。

repeat 泛策略

repeat 泛策略接受另一个策略,并不断应用它,直到失败, 或到它成功却不再有任何进展为止。
下面是用 repeat 证明 10 在一个长列表中的示例。
Theorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
  repeat (try (left; reflexivity); right).
Qed.
策略 repeat T 永不失败。 若策略 T 不能作用于原目标, 则 repeat 仍【成功】且完全不改变目标(即重复了零次)。
Theorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
  repeat simpl.
  repeat (left; reflexivity).
  repeat (right; try (left; reflexivity)).
Qed.
策略 repeat T 应用 T 的次数没有上界。若 T 是 【总是】成功(且有进展)的策略,则 repeat T 会永远循环。
Theorem repeat_loop : ∀ (m n : nat),
  m + n = n + m.
Proof.
  intros m n.
  (* 取消下一行注释即可看到死循环。此后你需要中断 Rocq 才能再次
     让它响应。(在 Proof General 中,C-c C-c 可做到。) *)

  (* repeat rewrite Nat.add_comm. *)
Admitted.
等等,我们刚刚是不是在 Rocq 里写了个死循环?!?
算是吧。
虽然 Rocq 项语言 Gallina 上的求值保证终止,【策略】求值却不保证。 但这并不影响 Rocq 的逻辑一致性。 repeat 等策略的工作是引导 Rocq 构造证明。 若构造过程发散(即不终止),那只表示我们完全没能 构造出证明,而非构造了一个坏证明。

练习: 3 stars,标准 (optimize_0plus_b_sound)

由于 optimize_0plus 变换不改变 aexp 的值, 可以把它应用到 bexp 中出现的所有 aexp 上, 而不改变 bexp 的值。请写出对 bexp 做此变换的函数并证明其可靠。 用我们刚见过的泛策略,使证明尽可能简短优雅。
Fixpoint optimize_0plus_b (b : bexp) : bexp
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Example optimize_0plus_b_test1:
  optimize_0plus_b (BNot (BGt (APlus (ANum 0) (ANum 4)) (ANum 8))) =
                   (BNot (BGt (ANum 4) (ANum 8))).
Proof. (* 在这里填写 *) Admitted.

Example optimize_0plus_b_test2:
  optimize_0plus_b (BAnd (BLe (APlus (ANum 0) (ANum 4)) (ANum 5)) BTrue) =
                   (BAnd (BLe (ANum 4) (ANum 5)) BTrue).
Proof. (* 在这里填写 *) Admitted.

Theorem optimize_0plus_b_sound : ∀ b,
  beval (optimize_0plus_b b) = beval b.
Proof.
  (* 在这里填写 *) Admitted.
☐

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

【设计练习】:optimize_0plus 函数实现的优化, 只是算术与布尔表达式上众多可能优化之一。 请写出更精巧的优化器并证明其正确。 (你多半会发现从小处着手最容易:先加一个简单的优化及其正确性 证明,再逐步增量到更有趣的东西。)
(* 在这里填写 *)
☐

定义新策略

Rocq 还提供了在策略脚本中「编程」的设施。
下面演示的 Ltac 习语,提供了一种便捷方式来定义「简写策略」。 它把多个策略打包进单条命令。
Ltac 还包括对目标与语境的语法模式匹配,以及一般编程设施。
它对证明自动化很有用,用 Ltac 编程也有若干习语。 由于你可能没见过这种语言风格,好的参考是教科书 "Certified Programming with Dependent Types" CPDT;它比本课程所需更深入,但被许多人 视为 Ltac 编程的最佳参考。
仅供日后参考:Rocq 还提供另外两种定义新策略的方式。其一是 Tactic Notation 命令,可自定义新策略的具体语法控制;其二是 可直接操纵 Rocq 内部结构的底层 API。就当前目的而言, 我们都不需要它们。
下面是一个名为 invert 的 Ltac 脚本示例。
Ltac invert H :=
  inversion H; subst; clear H.
这定义了一个名为 invert 的新策略,它以假设 H 为参数, 并执行命令序列 inversion H; subst; clear H。 这让我们能快速对证据与构造子做反演, 用生成的等式改写,并在最后删除多余假设。
Lemma invert_example1: ∀ {a b c: nat}, [a ;b] = [a;c] → b = c.
  intros.
  invert H.
  reflexivity.
Qed.

lia 策略

lia 策略实现了整数线性算术的判定过程。 这是命题逻辑与算术的一个子集。
若目标是由下列成分构成的全称量化公式:
  • 数值常量、加法(+ 与 S)、减法(- 与 pred)以及 与常量的乘法(这使它成为 Presburger 算术),
  • 相等(= 与 ≠)与序(≤ 与 >),以及
  • 逻辑联结词 ∧、∨、¬ 与 →,
那么调用 lia 要么解决目标,要么失败;失败意味着目标实际上为假。 (若目标【不是】这种形式,lia 会失败。)
Example silly_presburger_example : ∀ m n o p,
  m + n ≤ n + o ∧ o + 3 = p + 3 →
  m ≤ p.
Proof.
  intros. lia.
Qed.

Example add_comm__lia : ∀ m n,
    m + n = n + m.
Proof.
  intros. lia.
Qed.

Example add_assoc__lia : ∀ m n p,
    m + (n + p) = m + n + p.
Proof.
  intros. lia.
Qed.
(注意本文件顶部的 From Stdlib Require Import Lia., 它使 lia 可用。)

更多方便的策略

最后,这里有一些你可能觉得方便的杂项策略。
  • clear H:从语境中删除假设 H。
  • subst x:给定变量 x,在语境中找假设 x = e 或 e = x。 把语境与当前目标中的 x 全部替换为 e,并清除该假设。
  • subst:替换掉【所有】形如 x = e 或 e = x 的假设 (其中 x 为变量)。
  • rename... into...:更改证明语境中假设的名字。例如, 若语境含名为 x 的变量,则 rename x into y 会把 x 的所有出现改成 y。
  • assumption:尝试在语境中找恰好匹配目标的假设 H; 若找到,就解决该目标。
  • contradiction:尝试在语境中找逻辑上等价于 False 的假设 H。 若找到,就解决该目标。
  • constructor:尝试找一个构造子 c (来自当前环境中某个 Inductive 定义), 使其可应用于解决当前目标。若找到,其行为如同 apply c。
后文会看到所有这些的示例。

把求值作为关系

我们已把 aeval 与 beval 作为由 Fixpoint 定义的函数给出。 另一种思考求值的方式,且往往更灵活: 把它看作表达式与其值之间的【关系|Relation】。 这一视角会导出如下 Inductive 定义……
Module aevalR_first_try.

Inductive aevalR : aexp → nat → Prop :=
  | E_ANum (n : nat) :
      aevalR (ANum n) n
  | E_APlus (e1 e2 : aexp) (n1 n2 : nat) :
      aevalR e1 n1 →
      aevalR e2 n2 →
      aevalR (APlus e1 e2) (n1 + n2)
  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :
      aevalR e1 n1 →
      aevalR e2 n2 →
      aevalR (AMinus e1 e2) (n1 - n2)
  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :
      aevalR e1 n1 →
      aevalR e2 n2 →
      aevalR (AMult e1 e2) (n1 × n2).

Module HypothesisNames.
一点记法上的旁注。我们也可以这样写 aevalR 的定义, 为每个情形的假设给出显式名字:
Inductive aevalR : aexp → nat → Prop :=
  | E_ANum (n : nat) :
      aevalR (ANum n) n
  | E_APlus (e1 e2 : aexp) (n1 n2 : nat)
      (H1 : aevalR e1 n1)
      (H2 : aevalR e2 n2) :
      aevalR (APlus e1 e2) (n1 + n2)
  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat)
      (H1 : aevalR e1 n1)
      (H2 : aevalR e2 n2) :
      aevalR (AMinus e1 e2) (n1 - n2)
  | E_AMult (e1 e2 : aexp) (n1 n2 : nat)
      (H1 : aevalR e1 n1)
      (H2 : aevalR e2 n2) :
      aevalR (AMult e1 e2) (n1 × n2).
这种风格让我们对 Rocq 在涉及 aevalR 的证明中所选的名字 有更多控制,代价是定义稍显冗长。
给 aevalR 一个中缀记法会很方便。我们写 e ==> n 表示算术表达式 e 求值为值 n。
Notation "e '==>' n"
         := (aevalR e n)
            (at level 90, left associativity)
         : type_scope.

End aevalR_first_try.
正如我们在 IndProp 一章的正则表达式案例研究中所见, Rocq 提供了在 aevalR 定义本身中使用该记法的方式。

Inductive aevalR : aexp → nat → Prop :=
  | E_ANum (n : nat) :
      (ANum n) ==> n
  | E_APlus (e1 e2 : aexp) (n1 n2 : nat) :
      (e1 ==> n1) →
      (e2 ==> n2) →
      (APlus e1 e2) ==> (n1 + n2)
  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :
      (e1 ==> n1) →
      (e2 ==> n2) →
      (AMinus e1 e2) ==> (n1 - n2)
  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :
      (e1 ==> n1) →
      (e2 ==> n2) →
      (AMult e1 e2) ==> (n1 × n2)

  where "e '==>' n" := (aevalR e n) : type_scope.

推理规则记法

在非形式化讨论中,把 aevalR 及类似关系的规则, 写成更易读的【推理规则|Inference Rule】图形形式很方便。 横线上方的前提,为横线下方的结论提供依据。
例如,构造子 E_APlus……
      | E_APlus : ∀ (e1 e2 : aexp) (n1 n2 : nat),
          aevalR e1 n1 →
          aevalR e2 n2 →
          aevalR (APlus e1 e2) (n1 + n2)
……可写成如下推理规则:
e1 ==> n1
e2 ==> n2 (E_APlus)  

APlus e1 e2 ==> n1+n2
形式上,推理规则没什么深的:它们只是蕴含。
可以把右侧规则名读作构造子名,把横线上方前提之间(以及横线本身) 的每个换行读作 →。
规则中提到的所有变量(e1、n1 等)都由开头的全称量词隐式绑定。 (这类变量常称为【元变量|Metavariable】,以区别于我们正在定义的 语言中的变量。目前算术表达式还不含变量,但很快会加上。)
整个规则集合被理解为包在一个 Inductive 声明中。在非形式化行文中, 有时用类似「令 aevalR 为对下列规则封闭的最小关系……」的话来 表示这一点。
例如,我们可以把 ==> 定义为对这些规则封闭的最小关系:
   (E_ANum)  

ANum n ==> n
e1 ==> n1
e2 ==> n2 (E_APlus)  

APlus e1 e2 ==> n1+n2
e1 ==> n1
e2 ==> n2 (E_AMinus)  

AMinus e1 e2 ==> n1-n2
e1 ==> n1
e2 ==> n2 (E_AMult)  

AMult e1 e2 ==> n1*n2

练习: 1 star,标准,可选 (beval_rules)

这里再次给出 beval 函数的 Rocq 定义:
  Fixpoint beval (e : bexp) : bool :=
    match e with
    | BTrue ⇒ true
    | BFalse ⇒ false
    | BEq a1 a2 ⇒ (aeval a1) =? (aeval a2)
    | BNeq a1 a2 ⇒ negb ((aeval a1) =? (aeval a2))
    | BLe a1 a2 ⇒ (aeval a1) <=? (aeval a2)
    | BGt a1 a2 ⇒ negb ((aeval a1) <=? (aeval a2))
    | BNot b ⇒ negb (beval b)
    | BAnd b1 b2 ⇒ andb (beval b1) (beval b2)
    end.
请用推理规则记法写出布尔求值作为关系的相应定义。
(* 在这里填写 *)

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

定义的等价性

证明求值的关系式定义与函数式定义一致是直截了当的:
Theorem aevalR_iff_aeval : ∀ a n,
  (a ==> n) ↔ aeval a = n.
Proof.
  split.
  - (* -> *)
    intros H.
    induction H; simpl.
    + (* E_ANum *)
      reflexivity.
    + (* E_APlus *)
      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
    + (* E_AMinus *)
      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
    + (* E_AMult *)
      rewrite IHaevalR1. rewrite IHaevalR2. reflexivity.
  - (* <- *)
    generalize dependent n.
    induction a;
       simpl; intros; subst.
    + (* ANum *)
      apply E_ANum.
    + (* APlus *)
      apply E_APlus.
      × apply IHa1. reflexivity.
      × apply IHa2. reflexivity.
    + (* AMinus *)
      apply E_AMinus.
      × apply IHa1. reflexivity.
      × apply IHa2. reflexivity.
    + (* AMult *)
      apply E_AMult.
      × apply IHa1. reflexivity.
      × apply IHa2. reflexivity.
Qed.
同样,我们可以用一些泛策略把证明缩短不少。
Theorem aevalR_iff_aeval' : ∀ a n,
  (a ==> n) ↔ aeval a = n.
Proof.
  (* 已在课上完成 *)
  split.
  - (* -> *)
    intros H; induction H; subst; reflexivity.
  - (* <- *)
    generalize dependent n.
    induction a; simpl; intros; subst; constructor;
       try apply IHa1; try apply IHa2; reflexivity.
Qed.

练习: 3 stars,标准 (bevalR)

用与 aevalR 相同的风格写出关系 bevalR,并证明它与 beval 等价。
Inductive bevalR: bexp → bool → Prop :=
(* 在这里填写 *)
where "e '==>b' b" := (bevalR e b) : type_scope
.

Lemma bevalR_iff_beval : ∀ b bv,
  b ==>b bv ↔ beval b = bv.
Proof.
  (* 在这里填写 *) Admitted.
☐
End AExp.

计算式定义与关系式定义

对算术与布尔表达式的求值定义而言, 选函数式还是关系式主要是口味问题:两种都行。
然而,在许多情形下,求值的关系式定义比函数式好用得多。
Module aevalR_division.
例如,假设我们想用除法扩展算术运算:
Inductive aexp : Type :=
  | ANum (n : nat)
  | APlus (a1 a2 : aexp)
  | AMinus (a1 a2 : aexp)
  | AMult (a1 a2 : aexp)
  | ADiv (a1 a2 : aexp). (* <--- NEW *)
扩展 aeval 的定义来处理这个新运算并不直接 (ADiv (ANum 5) (ANum 0) 应返回什么作为结果?)。但扩展 aevalR 却很容易。

Inductive aevalR : aexp → nat → Prop :=
  | E_ANum (n : nat) :
      (ANum n) ==> n
  | E_APlus (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (APlus a1 a2) ==> (n1 + n2)
  | E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (AMinus a1 a2) ==> (n1 - n2)
  | E_AMult (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (AMult a1 a2) ==> (n1 × n2)
  | E_ADiv (a1 a2 : aexp) (n1 n2 n3 : nat) : (* <----- NEW *)
      (a1 ==> n1) → (a2 ==> n2) → (n2 > 0) →
      (mult n2 n3 = n1) → (ADiv a1 a2) ==> n3

where "a '==>' n" := (aevalR a n) : type_scope.
注意,这个求值关系对应一个【偏函数|Partial Function】: 有些输入它并不指定输出。
或者假设我们想用非确定性数生成器 any 扩算术运算。 它求值时可能产生任何数。
(这不同于在所有可能的数中作【概率】选择: 我们并未为结果指定任何特定概率分布,只是说哪些结果是【可能的】。)

Inductive aexp : Type :=
  | AAny (* <--- NEW *)
  | ANum (n : nat)
  | APlus (a1 a2 : aexp)
  | AMinus (a1 a2 : aexp)
  | AMult (a1 a2 : aexp).
同样,扩展 aeval 会很棘手。 现在求值【不是】从表达式到数的确定性函数;但扩展 aevalR 没问题……
Inductive aevalR : aexp → nat → Prop :=
  | E_Any (n : nat) :
      AAny ==> n (* <--- NEW *)
  | E_ANum (n : nat) :
      (ANum n) ==> n
  | E_APlus (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (APlus a1 a2) ==> (n1 + n2)
  | E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (AMinus a1 a2) ==> (n1 - n2)
  | E_AMult (a1 a2 : aexp) (n1 n2 : nat) :
      (a1 ==> n1) → (a2 ==> n2) → (AMult a1 a2) ==> (n1 × n2)

where "a '==>' n" := (aevalR a n) : type_scope.

End aevalR_extended.
此时你也许会想:默认该用哪种风格?
在我们刚看的示例里,关系式定义反而比函数式更有用。 对这类不易表达成函数、或确实【不是】函数的情形,并无真正选择。 但若两种风格都可行呢?
支持关系式定义的一点是:它们可以更优雅、更容易理解。
另一点是 Rocq 会从 Inductive 定义自动生成漂亮的反演与归纳法则。
另一方面,函数式定义往往更方便:
  • 函数自动是确定且全的;对关系式定义,若需要这些性质就必须 显式【证明】它们。
  • 有了函数,还能利用 Rocq 的计算机制在证明中化简表达式。
此外,函数可以直接从 Gallina「提取」为 OCaml 或 Haskell 的可执行代码。
最终,选择往往取决于具体情形,或干脆是口味问题。 在大型 Rocq 开发中,常见同一定义以函数式与关系式【两种】风格给出, 外加一条说明二者重合的引理。 后续证明可在两种视角间随意切换。

带变量的表达式

让我们回到 Imp 的定义;接下来要做的,是用变量丰富算术与布尔 表达式。
为保持简单,我们假设所有变量都是全局的,且只保存数。

状态

由于要查找变量以得到它们的当前值,我们会使用 Maps 一章中的 全映射。
一个【机器状态|Machine State】(或简称【状态|State】)表示程序 执行中某一时刻所有变量的当前值。
为简单起见,我们假设状态对【所有】变量都有定义。 尽管任何给定程序只能提到有限个变量。 每个变量存一个自然数,因此可以把状态表示为 从字符串(变量名)到 nat 的全映射,并在存储中用 0 作为默认值。
Definition state := total_map nat.

语法

我们只需再加一个构造子,就能给先前的算术表达式加上变量:
Inductive aexp : Type :=
  | ANum (n : nat)
  | AId (x : string) (* <--- NEW *)
  | APlus (a1 a2 : aexp)
  | AMinus (a1 a2 : aexp)
  | AMult (a1 a2 : aexp).
把几个变量名定义为记法简写会让示例更易读:
Definition W : string := "W".
Definition X : string := "X".
Definition Y : string := "Y".
Definition Z : string := "Z".
(这种为程序变量命名的约定(X、Y、Z), 与我们先前用大写字母表示类型略有冲突。 到 Imp 为止的章节并未大量使用多态, 这种重载不应造成混淆。)
bexp 的定义未变(只是现在引用新的 aexp):
Inductive bexp : Type :=
  | BTrue
  | BFalse
  | BEq (a1 a2 : aexp)
  | BNeq (a1 a2 : aexp)
  | BLe (a1 a2 : aexp)
  | BGt (a1 a2 : aexp)
  | BNot (b : bexp)
  | BAnd (b1 b2 : bexp).

记法

为使 Imp 程序更易读写,我们引入一些记法与隐式转换。
你无需确切理解这些声明做了什么。
简要而言:
  • Coercion 声明规定,函数(或构造子)可被类型系统隐式用于 把输入类型的值转换为输出类型的值。 例如,AId 的转换声明允许我们在需要 aexp 时直接写普通字符串。 该字符串会被隐式包装为 AId。
  • Declare Custom Entry com 让 Rocq 创建一套解析 Imp 表达式 与程序的「自定义文法」。其后的第一条记法声明告诉 Rocq, <{ 与 }> 之间的任何内容都应使用 Imp 文法解析。 同样,无需理解细节。但重要的是要意识到: 当 +/-/×/=/≤ 等熟悉的运算符出现在 <{ 与 }> 之间时, 我们是在为它们定义【新的】解释。
Coercion AId : string >-> aexp.
Coercion ANum : nat >-> aexp.

Declare Custom Entry com.
Declare Scope com_scope.

Notation "<{ e }>" := e
  (e custom com, format "'[hv' <{ '/ ' '[v' e ']' '/' }> ']'") : com_scope.

Notation "( x )" := x (in custom com, x at level 99).
Notation "x" := x (in custom com at level 0, x constr at level 0).

Notation "f x .. y" := (.. (f x) .. y)
                  (in custom com at level 0, only parsing,
                  f constr at level 0, x constr at level 1,
                      y constr at level 1).
Notation "x + y" := (APlus x y) (in custom com at level 50, left associativity).
Notation "x - y" := (AMinus x y) (in custom com at level 50, left associativity).
Notation "x * y" := (AMult x y) (in custom com at level 40, left associativity).
Notation "'true'" := true (at level 1).
Notation "'true'" := BTrue (in custom com at level 0).
Notation "'false'" := false (at level 1).
Notation "'false'" := BFalse (in custom com at level 0).
Notation "x <= y" := (BLe x y) (in custom com at level 70, no associativity).
Notation "x > y" := (BGt x y) (in custom com at level 70, no associativity).
Notation "x = y" := (BEq x y) (in custom com at level 70, no associativity).
Notation "x <> y" := (BNeq x y) (in custom com at level 70, no associativity).
Notation "x && y" := (BAnd x y) (in custom com at level 80, left associativity).
Notation "'~' b" := (BNot b) (in custom com at level 75, right associativity).

Open Scope com_scope.
现在我们可以写 3 + (X × 2) 而非 APlus 3 (AMult X 2), 写 true && ~(X ≤ 4) 而非 BAnd true (BNot (BLe X 4))。
Definition example_aexp : aexp := <{ 3 + (X × 2) }>.
Definition example_bexp : bexp := <{ true && ¬(X ≤ 4) }>.

求值

算术与布尔求值器现在必须扩展以处理变量。 做法很直接:把状态 st 作为额外参数:
Fixpoint aeval (st : state) (* <--- NEW *)
               (a : aexp) : nat :=
  match a with
  | ANum n ⇒ n
  | AId x ⇒ st x (* <--- NEW *)
  | <{a1 + a2}> ⇒ (aeval st a1) + (aeval st a2)
  | <{a1 - a2}> ⇒ (aeval st a1) - (aeval st a2)
  | <{a1 × a2}> ⇒ (aeval st a1) × (aeval st a2)
  end.

Fixpoint beval (st : state) (* <--- NEW *)
               (b : bexp) : bool :=
  match b with
  | <{true}> ⇒ true
  | <{false}> ⇒ false
  | <{a1 = a2}> ⇒ (aeval st a1) =? (aeval st a2)
  | <{a1 ≠ a2}> ⇒ negb ((aeval st a1) =? (aeval st a2))
  | <{a1 ≤ a2}> ⇒ (aeval st a1) <=? (aeval st a2)
  | <{a1 > a2}> ⇒ negb ((aeval st a1) <=? (aeval st a2))
  | <{¬ b1}> ⇒ negb (beval st b1)
  | <{b1 && b2}> ⇒ andb (beval st b1) (beval st b2)
  end.
我们可在状态这一特例中使用全映射的记法;即把空状态写成 (__ !-> 0)。
Definition empty_st := (__ !-> 0).
另外,我们可以为只有一个变量绑定到值的「单例状态」加记法。
Notation "x '!->' v" := (x !-> v ; empty_st) (at level 100, right associativity).

Example aexp1 :
    aeval (X !-> 5) <{ 3 + (X × 2) }>
  = 13.
Proof. reflexivity. Qed.
Example aexp2 :
    aeval (X !-> 5 ; Y !-> 4) <{ Z + (X × Y) }>
  = 20.
Proof. reflexivity. Qed.

Example bexp1 :
    beval (X !-> 5) <{ true && ¬(X ≤ 4) }>
  = true.
Proof. reflexivity. Qed.

命令

现在我们可以定义 Imp【命令|Command】(或【语句|Statement】) 的语法与行为了。

Syntax

非形式化地,命令 c 由下列 BNF 文法描述。
     c := skip
        | x := a
        | c ; c
        | if b then c else c end
        | while b do c end
下面是指令抽象语法的形式化定义:
Inductive com : Type :=
  | CSkip
  | CAsgn (x : string) (a : aexp)
  | CSeq (c1 c2 : com)
  | CIf (b : bexp) (c1 c2 : com)
  | CWhile (b : bexp) (c : com).
正如对表达式所做的那样,可以用几条 Notation 声明 让 Imp 程序的读写更方便。
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.
例如,下面是阶乘函数,写成 Rocq 形式化定义。当此命令终止时, 变量 Y 将含有 X 初值的阶乘。
Definition fact_in_coq : com :=
  <{ Z := X;
     Y := 1;
     while Z ≠ 0 do
       Y := Y × Z;
       Z := Z - 1
     end }>.

脱糖记法

Rocq 提供了丰富的特性来管理日益增长的复杂性, 例如转换与记法。但过度使用它们会让人难以理解所输入表达式的实际含义。 此时用下列命令「关掉」这些特性,往往能看清更基本的图景:
  • Unset Printing Notations(用 Set Printing Notations 撤销)
  • Set Printing Coercions(用 Unset Printing Coercions 撤销)
  • Set Printing All(用 Unset Printing All 撤销)
这些命令也可在证明中途使用,以展开当前目标与语境。
Unset Printing Notations.
Print fact_in_coq.
(* ===>
   fact_in_coq =
   CSeq (CAsgn Z X)
        (CSeq (CAsgn Y (S O))
              (CWhile (BNot (BEq Z O))
                      (CSeq (CAsgn Y (AMult Y Z))
                            (CAsgn Z (AMinus Z (S O))))))
        : com *)

Set Printing Notations.

Print example_bexp.
(* ===> example_bexp = <{(true && ~ (X <= 4))}> *)

Set Printing Coercions.
Print example_bexp.
(* ===> example_bexp = <{(true && ~ (AId X <= ANum 4))}> *)

Print fact_in_coq.
(* ===>
  fact_in_coq =
  <{ Z := (AId X);
     Y := (ANum 1);
     while ~ (AId Z) = (ANum 0) do
       Y := (AId Y) * (AId Z);
       Z := (AId Z) - (ANum 1)
     end }>
       : com *)

Unset Printing Coercions.

再谈 Locate

查找标识符

与标识符一起使用时,Locate 会打印作用域中同名每个值的完整路径。 这对排查变量遮蔽引起的问题很有用。
Locate aexp.
(* ===>
     Inductive LF.Imp.aexp
     Inductive LF.Imp.AExp.aexp
       (shorter name to refer to it in current context is AExp.aexp)
     Inductive LF.Imp.aevalR_division.aexp
       (shorter name to refer to it in current context is aevalR_division.aexp)
     Inductive LF.Imp.aevalR_extended.aexp
       (shorter name to refer to it in current context is aevalR_extended.aexp)
*)

查找记法

遇到未知记法时,可以用 Locate 加上含其某一符号的字符串, 查看它可能的解释。
Locate "&&".
(* ===>
    Notation
      "x && y" := BAnd x y (default interpretation)
      "x && y" := andb x y : bool_scope (default interpretation)
*)

Locate ";".
(* ===>
    Notation
      "x '⊢>' v ';' m" := (update m x v) (default interpretation)
      "x ; y" := (CSeq x y) (default interpretation)
      "x '!->' v ';' m" := (t_update m x v) (default interpretation)
      " x ; y ; .. ; z " := cons x (cons y .. (cons z nil) ..) : list_scope
      (default interpretation) *)


Locate "while".
(* ===>
    Notation
      "'while' x 'do' y 'end'" :=
          (CWhile x y) (default interpretation)
*)

更多示例

赋值:

Definition plus2 : com :=
  <{ X := X + 2 }>.

Definition XtimesYinZ : com :=
  <{ Z := X × Y }>.

循环

Definition subtract_slowly_body : com :=
  <{ Z := Z - 1 ;
     X := X - 1 }>.

Definition subtract_slowly : com :=
  <{ while X ≠ 0 do
       subtract_slowly_body
     end }>.

Definition subtract_3_from_5_slowly : com :=
  <{ X := 3 ;
     Z := 5 ;
     subtract_slowly }>.

一个无限循环:

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

对命令求值

接下来要定义对 Imp 命令求值是什么意思。while 循环未必终止 这一事实使定义求值函数变得棘手……

把求值作为函数(失败的尝试)

这是一次为命令定义求值函数的尝试(while 情形是假的)。
Fixpoint ceval_fun_no_while (st : state) (c : com) : state :=
  match c with
    | <{ skip }> ⇒
        st
    | <{ x := a }> ⇒
        (x !-> aeval st a ; st)
    | <{ c1 ; c2 }> ⇒
        let st' := ceval_fun_no_while st c1 in
        ceval_fun_no_while st' c2
    | <{ if b then c1 else c2 end}> ⇒
        if (beval st b)
          then ceval_fun_no_while st c1
          else ceval_fun_no_while st c2
    | <{ while b do c end }> ⇒
        st (* 假的 *)
  end.
在 OCaml 或 Haskell 这类更传统的函数式语言中,我们可以这样加 while 情形:
        Fixpoint ceval_fun (st : state) (c : com) : state :=
          match c with
            ...
            | <{ while b do c end}> =>
                if (beval st b)
                  then ceval_fun st <{c ; while b do c end}>
                  else st
          end.
Rocq 不接受这种定义("Error: Cannot guess decreasing argument of fix"),因为我们想定义的函数并不保证终止。确实,它【并不】 总是终止:例如,完整的 ceval_fun 作用于上面的 loop 程序 就永远不会终止。由于 Rocq 既要成为函数式语言,也要成为逻辑 一致的系统,任何可能不终止的函数都需要被拒绝。
下面是若允许不终止递归函数会出什么问题的示例:
         Fixpoint loop_false (n : nat) : False := loop_false n.
像 False 这样的命题会变得可证 (loop_false 0 会是 False 的一个证明)。 这将摧毁 Rocq 的逻辑一致性。
由于它在所有输入上都不终止,ceval_fun 无法在 Rocq 中写出。 至少不能在没有额外技巧与变通的情况下写出 (若好奇,见 ImpCEvalFun 一章)。

把求值作为关系

这里有个更好的办法:把 ceval 定义为【关系】而非【函数】; 即让其结果是 Prop 而非 state,类似我们上面为 aevalR 所做的那样。
这是一个重要改变。除了把我们从别扭的变通中解放出来, 它还给定义带来多得多的灵活性。 例如,若给语言加上 any 这样的非确定性特征, 我们希望求值的定义也是非确定性的。 它不仅不会是全的,甚至不会是函数!
我们将用记法 st =[ c ]=> st' 表示 ceval 关系。 st =[ c ]=> st' 表示在起始状态 st 下执行程序 c, 得到结束状态 st'。可读作「c 把状态 st 变为 st'」。

操作语义

下面是非形式化的求值定义,为可读性写成推理规则:
   (E_Skip)  

st =[ skip ]=> st
aeval st a = n (E_Asgn)  

st =[ x := a ]=> (x !-> n ; st)
st =[ c1 ]=> st'
st' =[ c2 ]=> st'' (E_Seq)  

st =[ c1;c2 ]=> st''
beval st b = true
st =[ c1 ]=> st' (E_IfTrue)  

st =[ if b then c1 else c2 end ]=> st'
beval st b = false
st =[ c2 ]=> st' (E_IfFalse)  

st =[ if b then c1 else c2 end ]=> st'
beval st b = false (E_WhileFalse)  

st =[ while b do c end ]=> st
beval st b = true
st =[ c ]=> st'
st' =[ while b do c end ]=> st'' (E_WhileTrue)  

st =[ while b do c end ]=> st''
下面是形式化定义。请确保你理解它如何与推理规则对应。

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 "st0 =[ c ]=> st1" := (ceval c st0 st1).
把求值定义成关系而非函数的代价是: 现在需要为某个程序求值到某个结果状态【构造证明】, 而不能只让 Rocq 的计算机制替我们做。
Example ceval_example1:
  empty_st =[
     X := 2;
     if (X ≤ 1)
       then Y := 3
       else Z := 4
     end
  ]=> (Z !-> 4 ; X !-> 2).
Proof.
  (* 我们必须提供中间状态 *)
  apply E_Seq with (X !-> 2).
  - (* 赋值命令 *)
    apply E_Asgn. reflexivity.
  - (* if 命令 *)
    apply E_IfFalse.
    + reflexivity.
    + apply E_Asgn. reflexivity.
Qed.

练习: 2 stars,标准 (ceval_example2)

Example ceval_example2:
  empty_st =[
    X := 0;
    Y := 1;
    Z := 2
  ]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).
Proof.
  (* 在这里填写 *) Admitted.
☐
Set Printing Implicit.
Check @ceval_example2.

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

写一个 Imp 程序,把从 1 到 X 的数(含端点:1 + 2 + ... + X) 求和放入变量 Y。你的程序应像定理 pup_to_2_ceval 所示那样更新 状态;你可以从它反推出应写的程序。该定理的证明会相当长。
Definition pup_to_n : com
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Theorem pup_to_2_ceval :
  (X !-> 2) =[
    pup_to_n
  ]=> (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).
Proof.
  (* 在这里填写 *) Admitted.
☐

求值的确定性

把求值从计算式定义改为关系式定义是好做法, 因为它把我们从「求值必须是全函数」的人工要求中解放出来。 但它也提出一个问题:求值的第二种定义真的是偏【函数】吗? 还是有可能从同一状态 st 出发,以不同方式求值某命令 c, 到达两个不同的输出状态 st1 与 st2?
这不可能发生:ceval【是】一个偏函数:
Theorem ceval_deterministic: ∀ c st st1 st2,
     st =[ c ]=> st1 →
     st =[ c ]=> st2 →
     st1 = st2.
Proof.
  intros c st st1 st2 E1 E2.
  generalize dependent st2.
  induction E1; intros st2 E2; inversion E2; subst.
  - (* E_Skip *) reflexivity.
  - (* E_Asgn *) reflexivity.
  - (* E_Seq *)
    rewrite (IHE1_1 st'0 H1) in ×.
    apply IHE1_2. assumption.
  - (* E_IfTrue, b evaluates to true *)
      apply IHE1. assumption.
  - (* E_IfTrue,  b evaluates to false (contradiction) *)
      rewrite H in H5. discriminate.
  - (* E_IfFalse, b evaluates to true (contradiction) *)
      rewrite H in H5. discriminate.
  - (* E_IfFalse, b evaluates to false *)
      apply IHE1. assumption.
  - (* E_WhileFalse, b evaluates to false *)
    reflexivity.
  - (* E_WhileFalse, b evaluates to true (contradiction) *)
    rewrite H in H2. discriminate.
  - (* E_WhileTrue, b evaluates to false (contradiction) *)
    rewrite H in H4. discriminate.
  - (* E_WhileTrue, b evaluates to true *)
    rewrite (IHE1_1 st'0 H3) in ×.
    apply IHE1_2. assumption. Qed.

对 Imp 程序进行推理

在 Programming Language Foundations 中我们会进入更系统、 更强大的 Imp 程序推理技术;但仅凭裸定义,我们已经能做几件事 (尽管方式相当底层)。本节探讨一些示例。
Theorem plus2_spec : ∀ st n st',
  st X = n →
  st =[ plus2 ]=> st' →
  st' X = n + 2.
Proof.
  intros st n st' HX Heval.
对 Heval 做反演本质上迫使 Rocq 展开 ceval 计算的一步; 在此情形下它揭示 st' 必须是 st 用 X 的新值扩展而来, 因为 plus2 是赋值。
  inversion Heval. subst. clear Heval. simpl.
  apply t_update_eq. Qed.

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

陈述并证明 XtimesYinZ 的一个规约。
(* 在这里填写 *)

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

练习: 3 stars,标准,特别有用 (loop_never_stops)

Theorem loop_never_stops : ∀ st st',
  ~(st =[ loop ]=> st').
Proof.
  intros st st' contra. unfold loop in contra.
  remember <{ while true do skip end }> as loopdef
           eqn:Heqloopdef.
对所假定的表明 loopdef 终止的导出式做归纳。多数情形立即 矛盾,因此可用 discriminate 一步解决。
  (* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (no_whiles_eqv)

考虑下列函数:
Fixpoint no_whiles (c : com) : bool :=
  match c with
  | <{ skip }> ⇒
      true
  | <{ _ := _ }> ⇒
      true
  | <{ c1 ; c2 }> ⇒
      andb (no_whiles c1) (no_whiles c2)
  | <{ if _ then ct else cf end }> ⇒
      andb (no_whiles ct) (no_whiles cf)
  | <{ while _ do _ end }> ⇒
      false
  end.
这个谓词仅对不含 while 循环的程序给出 true。用 Inductive 写出性质 no_whilesR,使得 no_whilesR c 恰在 c 是无 while 循环程序时可证。然后证明它与 no_whiles 等价。
Inductive no_whilesR: com → Prop :=
 (* 在这里填写 *)
.

Theorem no_whiles_eqv:
  ∀ c, no_whiles c = true ↔ no_whilesR c.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 4 stars,标准 (no_whiles_terminating)

不含 while 循环的 Imp 程序总是终止。请陈述并证明说明这一点的 定理 no_whiles_terminating。 按你的喜好使用 no_whiles 或 no_whilesR。
(* 在这里填写 *)

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

附加练习

练习: 3 stars,标准 (stack_compiler)

老式 HP 计算器、Forth 与 Postscript 之类的语言, 以及 Java 虚拟机之类的抽象机,都用【栈|Stack】求值算术表达式。 例如,表达式
      (2*3)+(3*(4-2))
会写成
      2 3 * 3 4 2 - * +
并这样求值(右侧是要执行的程序,左侧是栈的内容):
      [ ]           |    2 3 * 3 4 2 - * +
      [2]           |    3 * 3 4 2 - * +
      [3, 2]        |    * 3 4 2 - * +
      [6]           |    3 4 2 - * +
      [3, 6]        |    4 2 - * +
      [4, 3, 6]     |    2 - * +
      [2, 4, 3, 6]  |    - * +
      [2, 3, 6]     |    * +
      [6, 6]        |    +
      [12]          |
本练习的目标是写一个小编译器,把 aexp 翻译成栈机指令。
我们的栈语言指令集将由下列指令组成:
  • SPush n:把数 n 压入栈。
  • SLoad x:从存储中取出标识符 x 并压入栈。
  • SPlus: 弹出栈顶两个数,相加,再把结果压回栈。
  • SMinus: 类似,但用第二个数减去第一个。
  • SMult: 类似,但是相乘。
Inductive sinstr : Type :=
| SPush (n : nat)
| SLoad (x : string)
| SPlus
| SMinus
| SMult.
写一个函数来执行栈语言中的程序。 它以状态、表示为数列表的栈(栈顶是列表头)、 以及表示为指令列表的程序为输入,并返回执行程序后的栈。 请在下面的示例上测试你的函数。
注意:当栈中元素少于两个却遇到 SPlus、SMinus 或 SMult 指令时该怎么做,并未指定。 正确的编译器永远不会产生这样的畸形程序。 但为了后面的练习,最好跳过出错的指令并继续下一条。
Fixpoint s_execute (st : state) (stack : list nat)
                   (prog : list sinstr)
                 : list nat
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.

Check s_execute.

Example s_execute1 :
     s_execute empty_st []
       [SPush 5; SPush 3; SPush 1; SMinus]
   = [2; 5].
(* 在这里填写 *) Admitted.

Example s_execute2 :
     s_execute (X !-> 3) [3;4]
       [SPush 4; SLoad X; SMult; SPlus]
   = [15; 4].
(* 在这里填写 *) Admitted.
接下来,写一个把 aexp 编译成栈机程序的函数。运行该程序的 效果应与把表达式的值压栈相同。
Fixpoint s_compile (e : aexp) : list sinstr
  (* 将本行替换成 ":= 【你的定义】 ." *). Admitted.
定义 s_compile 之后,证明下列内容以检验它是否工作。
Example s_compile1 :
  s_compile <{ X - (2 × Y) }>
  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].
(* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (execute_app)

执行可在下列意义下分解:执行栈程序 p1 ++ p2 等同于执行 p1, 取得到的栈,再从该栈执行 p2。请证明这一事实。
Theorem execute_app : ∀ st p1 p2 stack,
  s_execute st stack (p1 ++ p2) = s_execute st (s_execute st stack p1) p2.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 3 stars,标准 (stack_compiler_correct)

现在我们证明上一练习中实现的编译器的正确性。先证明下列引理。 若变得困难,考虑你的 s_execute 或 s_compile 实现能否化简。
Lemma s_compile_correct_aux : ∀ st e stack,
  s_execute st stack (s_compile e) = aeval st e :: stack.
Proof.
  (* 在这里填写 *) Admitted.
主定理应是那条引理非常容易的推论。
Theorem s_compile_correct : ∀ (st : state) (e : aexp),
  s_execute st [] (s_compile e) = [ aeval st e ].
Proof.
  (* 在这里填写 *) Admitted.
☐

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

多数现代语言对布尔 and 使用「短路」求值规则:求值 BAnd b1 b2 时先求值 b1。若它求值为 false,则整个 BAnd 表达式立即 求值为 false,不再求值 b2。否则求值 b2 以确定 BAnd 表达式的结果。
写出 beval 的另一个版本,按这种方式对 BAnd 做短路求值, 并证明它与 beval 等价。 (这只因 Imp 中的表达式求值相当简单才成立。 在求值可能发散的更大语言中,短路的 BAnd【不会】与原来等价, 因为它会让更多程序终止。)
(* 在这里填写 *)
☐
Module BreakImp.

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

C 与 Java 之类的命令式语言常包含 break 或类似语句来中断循环 执行。本练习考虑如何给 Imp 加上 break。首先,我们需要用一个 额外情形来丰富命令语言。
Inductive com : Type :=
  | CSkip
  | CBreak (* <--- NEW *)
  | CAsgn (x : string) (a : aexp)
  | CSeq (c1 c2 : com)
  | CIf (b : bexp) (c1 c2 : com)
  | CWhile (b : bexp) (c : com).

Notation "'break'" := CBreak (in custom com at level 0) : com_scope.
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.
接下来,我们需要定义 break 的行为。 非形式化地:每当在命令序列中执行 break 时,它停止该序列的执行, 并发出信号表明最内层外层循环应终止。 (若没有任何外层循环,则整个程序直接终止。) 最终状态应与执行 break 语句时的状态相同。
一个重要点是:break 外有多个循环时该怎么做。 此时 break 应只终止【最内层】循环。于是执行下列程序后……
       X := 0;
       Y := 1;
       while 0 ≠ Y do
         while true do
           break
         end;
         X := 1;
         Y := Y - 1
       end
…… X 的值应为 1,而非 0。
表达此行为的一种方式: 给求值关系再加一个参数,指明命令的求值是否执行了 break 语句:
Inductive result : Type :=
  | SContinue
  | SBreak.

直观地,st =[ c ]=> st' / s 表示: 若在状态 st 下启动 c,则它在状态 st' 终止, 并发出信号表明最内层外层循环(或整个程序)应立即退出 (s = SBreak),或表明执行应正常继续(s = SContinue)。
关系「st =[ c ]=> st' / s」的定义, 与上面给出的普通求值关系(st =[ c ]=> st')非常相似; 只需恰当地处理终止信号:
  • 若命令是 skip,状态不变,任何外层循环的执行都可正常继续。
  • 若命令是 break,状态不变,但我们发出 SBreak 信号。
  • 若命令是赋值,则相应更新状态中该变量的绑定,并发出可正常继续 执行的信号。
  • 若命令形如 if b then c1 else c2 end,则按 Imp 原语义更新 状态,只是我们还从实际走的分支的执行中传播其信号。
  • 若命令是序列 c1 ; c2,先执行 c1。若得到 SBreak, 跳过 c2 的执行,并把 SBreak 信号传播到外层语境; 结果状态与只执行 c1 得到的状态相同。否则,在执行 c1 后得到的状态上执行 c2,并传播那里产生的信号。
  • 最后,对形如 while b do c end 的循环,语义几乎与以前相同。 唯一区别是:当 b 求值为真时,我们执行 c 并检查它发出的 信号。若信号是 SContinue,则按原语义继续;否则停止循环 执行,结果状态与执行当前迭代得到的状态相同。无论哪种情况, 由于 break 只终止最内层循环,while 发出 SContinue。
根据上述描述,补全 ceval 关系的定义。
Inductive ceval : com → state → result → state → Prop :=
  | E_Skip : ∀ st,
      st =[ CSkip ]=> st / SContinue
  (* 在这里填写 *)

  where "st '=[' c ']=>' st' '/' s" := (ceval c st s st').
现在证明你的 ceval 定义的下列性质:
Theorem break_ignore : ∀ c st st' s,
     st =[ break; c ]=> st' / s →
     st = st'.
Proof.
  (* 在这里填写 *) Admitted.

Theorem while_continue : ∀ b c st st' s,
  st =[ while b do c end ]=> st' / s →
  s = SContinue.
Proof.
  (* 在这里填写 *) Admitted.

Theorem while_stops_on_break : ∀ b c st st',
  beval st b = true →
  st =[ c ]=> st' / SBreak →
  st =[ while b do c end ]=> st' / SContinue.
Proof.
  (* 在这里填写 *) Admitted.

Theorem seq_continue : ∀ c1 c2 st st' st'',
  st =[ c1 ]=> st' / SContinue →
  st' =[ c2 ]=> st'' / SContinue →
  st =[ c1 ; c2 ]=> st'' / SContinue.
Proof.
  (* 在这里填写 *) Admitted.

Theorem seq_stops_on_break : ∀ c1 c2 st st',
  st =[ c1 ]=> st' / SBreak →
  st =[ c1 ; c2 ]=> st' / SBreak.
Proof.
  (* 在这里填写 *) Admitted.
☐

练习: 3 stars,高级,可选 (while_break_true)

Theorem while_break_true : ∀ b c st st',
  st =[ while b do c end ]=> st' / SContinue →
  beval st' b = true →
  ∃ st'', st'' =[ c ]=> st' / SBreak.
Proof.
(* 在这里填写 *) Admitted.
☐

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

Theorem ceval_deterministic: ∀ (c:com) st st1 st2 s1 s2,
     st =[ c ]=> st1 / s1 →
     st =[ c ]=> st2 / s2 →
     st1 = st2 ∧ s1 = s2.
Proof.
  (* 在这里填写 *) Admitted.
☐
End BreakImp.

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

给命令语言加上 C 风格的 for 循环,更新 ceval 定义以给出 for 循环的语义,并按需为 for 循环加情形, 使本文件中所有证明都能被 Rocq 接受。
for 循环应由下列成分参数化: (a) 最初执行的语句, (b) 循环每轮运行以决定是否继续的测试, (c) 每轮结束时执行的语句, (d) 构成循环体的语句。 (你不必为 for 循环发明具体 Notation,但若愿意也可以玩一玩。)
(* 在这里填写 *)
☐
(* 2026-11-26 15:54 *)