PE部分求值

(* 本章由單中杰(Chung-chieh Shan)撰写并维护。 *)
Equiv 一章介绍了【常量折叠|Constant Folding】作为 程序变换的一个示例,并证明了它保持程序的含义。 常量折叠作用于显式常量,例如 ANum 表达式。 比如,它把命令 Y := 3 + 1 化简为 Y := 4。 然而,它不会顺着数据流传播已知常量。 例如,它不会把语句序列
      X := 3; Y := X + 1 化简为
      X := 3; Y := 4 因为处理到 Y 时它已经忘记 X 是 3。
我们自然想改进常量折叠,让它传播已知常量并用它们化简程序。 这样做就构成了【部分求值|Partial Evaluation】的一种初级形式。 部分求值之所以得名,是因为它就像在运行程序。 只是程序只有一部分可被求值, 因为只有一部分输入是已知的。 例如,在不知道 Y 初始值的情况下,我们只能把程序
      X := 3; Y := (X + 1) - Y 化简为
      X := 3; Y := 4 - Y 。
From PLF Require Import Maps.
From Stdlib Require Import Bool.
From Stdlib Require Import Arith.
From Stdlib Require Import EqNat.
From Stdlib Require Import PeanoNat. Import Nat.
From Stdlib Require Import Lia.
From Stdlib Require Import FunctionalExtensionality.
From Stdlib Require Import List.
Import ListNotations.

Set Warnings "-parsing".
From PLF Require Import Smallstep.
From PLF Require Import Imp.

一般化的常量折叠

部分求值的出发点是表示我们关于状态的部分知识。 例如,在上面两个赋值之间,部分求值器可能只知道 X 是 3, 而对其他变量一无所知。

【部分状态|Partial State】

从概念上讲,我们可以把这样的部分状态看作类型 string → option nat(相对于具体全状态的类型 string → nat)。 除了查找与更新部分状态中各变量的值, 还想比较两个部分状态。 看它们是否以及在何处不同, 以处理条件控制流。 无法以这种方式比较两个任意函数。 因此用更具体的格式表示部分状态: 作为 string × nat 序对的列表。
Definition pe_state := list (string × nat).
其思想是:一个(类型为 string 的)变量出现在列表中, 当且仅当我们知道它当前的 nat 值。 pe_lookup 函数由此解释这一具体表示。 (若同一变量在列表中出现多次,以第一次出现为准; 但我们会把部分求值器定义为永不构造这样的 pe_state。)
Fixpoint pe_lookup (pe_st : pe_state) (V:string) : option nat :=
  match pe_st with
  | [] ⇒ None
  | (V',n')::pe_st ⇒ if String.eqb V V' then Some n'
                      else pe_lookup pe_st V
  end.
例如,empty_pe_state 表示对每个变量完全无知, 即把每个标识符都映射到 None 的函数。
Definition empty_pe_state : pe_state := [].
更一般地,若表示 pe_state 的 list 不含某个标识符, 则该 pe_state 必须把该标识符映射到 None。 在证明这一事实之前,我们先定义一个对 string 等式推理的有用策略。 策略
      compare V V' 表示对 String.eqb V V' 分情形推理。 在 V = V' 的情形下,该策略会把 V' 处处替换为 V。
Tactic Notation "compare" ident(i) ident(j) :=
  let H := fresh "Heq" i j in
  destruct (String.eqb_spec i j) as [H|H];
  [ subst j | ].

Theorem pe_domain: ∀ pe_st V n,
  pe_lookup pe_st V = Some n →
  In V (map (@fst _ _) pe_st).
Proof. intros pe_st V n H. induction pe_st as [| [V' n'] pe_st].
  - (*  *) inversion H.
  - (* :: *) simpl in H. simpl. compare V V'; auto. Qed.
接下来,我们会大量使用标准库中的 In 性质 (它也在 Logic.v 中定义过):
Print In.
(* ===> Fixpoint In {A:Type} (a: A) (l:list A) : Prop :=
           match l with
           |  => False
           | b :: m => b = a \/ In a m
            end
        : forall A : Type, A -> list A -> Prop *)

除了我们已见过的关于 In 的各种引理之外, 下面这条(取自标准库)也会有用:
Check filter_In.
(* ===> filter_In : forall (A : Type) (f : A -> bool) (x : A) (l : list A),
            In x (filter f l) <-> In x l /\ f x = true  *)

若类型 A 有测试元素相等的运算符 eqb, 我们就可以计算布尔值 inb eqb a l 来测试 In a l 是否成立。
Fixpoint inb {A : Type} (eqb : A → A → bool) (a : A) (l : list A) :=
  match l with
  | [] ⇒ false
  | a'::l' ⇒ eqb a a' || inb eqb a l'
  end.
用 reflect 性质容易把 inb 与 In 联系起来:
Lemma inbP : ∀ A : Type, ∀ eqb : A→A→bool,
  (∀ a1 a2, reflect (a1 = a2) (eqb a1 a2)) →
  ∀ a l, reflect (In a l) (inb eqb a l).
Proof.
  intros A eqb beqP a l.
  induction l as [|a' l' IH].
  - constructor. intros [].
  - simpl. destruct (beqP a a').
    + subst. constructor. left. reflexivity.
    + simpl. destruct IH; constructor.
      × right. trivial.
      × intros [H1 | H2]; congruence.
Qed.

【算术表达式|Arithmetic Expression】

对 aexp 的部分求值很直接。 它基本与常量折叠 fold_constants_aexp 相同。 只是有时部分状态会告诉我们某变量的当前值, 于是可用常量表达式替换它。
Fixpoint pe_aexp (pe_st : pe_state) (a : aexp) : aexp :=
  match a with
  | ANum n ⇒ ANum n
  | AId i ⇒ match pe_lookup pe_st i with (* <----- NEW *)
             | Some n ⇒ ANum n
             | None ⇒ AId i
             end
  | <{ a1 + a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ ANum (n1 + n2)
      | (a1', a2') ⇒ <{ a1' + a2' }>
      end
  | <{ a1 - a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ ANum (n1 - n2)
      | (a1', a2') ⇒ <{ a1' - a2' }>
      end
  | <{ a1 × a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ ANum (n1 × n2)
      | (a1', a2') ⇒ <{ a1' × a2' }>
      end
  end.
这个部分求值器折叠常量,但不运用加法的结合律。
Example test_pe_aexp1:
  pe_aexp [(X,3)] <{X + 1 + Y}>
  = <{4 + Y}>.
Proof. reflexivity. Qed.

Example text_pe_aexp2:
  pe_aexp [(Y,3)] <{X + 1 + Y}>
  = <{X + 1 + 3}>.
Proof. reflexivity. Qed.
现在,pe_aexp 在何种意义上是正确的? 把 pe_aexp 的正确性定义如下是合理的: 只要全状态 st:state 与部分状态 pe_st:pe_state 相容, 在 st 中对 a 求值 与对 pe_aexp pe_st a 求值结果相同。 这里相容是指:pe_st 赋了值的每个变量, 在 st 中都被赋了相同的值。 这一陈述确实成立。
Definition pe_consistent (st:state) (pe_st:pe_state) :=
  ∀ V n, Some n = pe_lookup pe_st V → st V = n.

Theorem pe_aexp_correct_weak: ∀ st pe_st, pe_consistent st pe_st →
  ∀ a, aeval st a = aeval st (pe_aexp pe_st a).
Proof. unfold pe_consistent. intros st pe_st H a.
  induction a; simpl;
    try reflexivity;
    try (destruct (pe_aexp pe_st a1);
         destruct (pe_aexp pe_st a2);
         rewrite IHa1; rewrite IHa2; reflexivity).
  (* 与 fold_constants_aexp_sound 相比,
     唯一有趣的情形是 AId *)

  - (* AId *)
    remember (pe_lookup pe_st x) as l. destruct l.
    + (* Some *) rewrite H with (n:=n) by apply Heql. reflexivity.
    + (* None *) reflexivity.
Qed.
然而,我们很快会希望部分求值器能消去赋值。 例如,它会把
    X := 3; Y := X - Y; X := 4 化简为
    Y := 3 - Y; X := 4 做法是把对 X 的赋值推迟到末尾。为完成这一化简, 我们需要对
    pe_aexp [(X,3)] (X - Y) 做部分求值的结果等于 3 - Y,而非原表达式 X - Y。 毕竟,把
    X := 3; Y := X - Y; X := 4 变换成
    Y := X - Y; X := 4 会是不正确的,而不只是低效。 输出表达式 3 - Y 与 X - Y 都满足我们刚证明的正确性标准。 确实,若我们只是定义 pe_aexp pe_st a = a, 定理 pe_aexp_correct_weak 本已平凡地成立。
取而代之,想在更强的意义上证明 pe_aexp 正确。 对部分求值产生的表达式求值 (aeval st (pe_aexp pe_st a)), 不得依赖全状态 st 中 已被部分状态 pe_st 指定的那些部分。 更精确地说,我们定义函数 pe_override,它用 pe_st 的内容 更新 st。换言之,pe_override 把 pe_st 中列出的赋值 施加到 st 之上。
Fixpoint pe_update (st:state) (pe_st:pe_state) : state :=
  match pe_st with
  | [] ⇒ st
  | (V,n)::pe_st ⇒ t_update (pe_update st pe_st) V n
  end.

Example test_pe_update:
  pe_update (Y !-> 1) [(X,3);(Z,2)]
  = (X !-> 3 ; Z !-> 2 ; Y !-> 1).
Proof. reflexivity. Qed.
尽管 pe_update 操作的是表示 pe_state 的具体 list, 其行为完全由 pe_lookup 对 pe_state 的解释决定。
(* eqb_neq 的一个方便推论 *)
Theorem false_eqb_string : ∀ x y : string,
   x ≠ y → String.eqb x y = false.
Proof.
  intros x y. rewrite String.eqb_neq.
  intros H. apply H. Qed.

Theorem pe_update_correct: ∀ st pe_st V0,
  pe_update st pe_st V0 =
  match pe_lookup pe_st V0 with
  | Some n ⇒ n
  | None ⇒ st V0
  end.
Proof. intros. induction pe_st as [| [V n] pe_st]. reflexivity.
  simpl in ×. unfold t_update.
  compare V0 V; auto. rewrite String.eqb_refl; auto. rewrite false_eqb_string; auto. Qed.
我们可以用两种方式把 pe_consistent 与 pe_update 联系起来。 其一,用部分状态覆写一个状态,总是得到与该部分状态相容的状态。 其二,若某状态已与部分状态相容,则再用该部分状态覆写它, 得到的仍是同一状态。
Theorem pe_update_consistent: ∀ st pe_st,
  pe_consistent (pe_update st pe_st) pe_st.
Proof. intros st pe_st V n H. rewrite pe_update_correct.
  destruct (pe_lookup pe_st V); inversion H. reflexivity. Qed.

Theorem pe_consistent_update: ∀ st pe_st,
  pe_consistent st pe_st → ∀ V, st V = pe_update st pe_st V.
Proof. intros st pe_st H V. rewrite pe_update_correct.
  remember (pe_lookup pe_st V) as l. destruct l; auto. Qed.
现在我们可以陈述并证明 pe_aexp 在更强意义下正确, 这将帮助我们定义部分求值器的其余部分。
直观上,用部分求值运行程序是两阶段过程。 第一阶段(【静态】阶段)针对某部分状态 对给定程序做部分求值,得到【剩余】程序。 第二阶段(【动态】阶段) 针对状态的其余部分对剩余程序求值。 动态状态为静态(部分)状态中未知的变量提供值。 因此,剩余程序应等价于把部分状态中列出的赋值 【前置】到原程序之前。
Theorem pe_aexp_correct: ∀ (pe_st:pe_state) (a:aexp) (st:state),
  aeval (pe_update st pe_st) a = aeval st (pe_aexp pe_st a).
Proof.
  intros pe_st a st.
  induction a; simpl;
    try reflexivity;
    try (destruct (pe_aexp pe_st a1);
         destruct (pe_aexp pe_st a2);
         rewrite IHa1; rewrite IHa2; reflexivity).
  (* 与 fold_constants_aexp_sound 相比,
     唯一有趣的情形是 AId。 *)

  rewrite pe_update_correct. destruct (pe_lookup pe_st x); reflexivity.
Qed.

【布尔表达式|Boolean Expression】

对布尔表达式的部分求值与之相似。(事实上,它与布尔表达式的 常量折叠完全类似,因为我们的语言没有布尔变量。)
Fixpoint pe_bexp (pe_st : pe_state) (b : bexp) : bexp :=
  match b with
  | <{ true }> ⇒ <{ true }>
  | <{ false }> ⇒ <{ false }>
  | <{ a1 = a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ if n1 =? n2 then <{ true }> else <{ false }>
      | (a1', a2') ⇒ <{ a1' = a2' }>
      end
  | <{ a1 ≠ a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ if negb (n1 =? n2) then <{ true }> else <{ false }>
      | (a1', a2') ⇒ <{ a1' ≠ a2' }>
      end
  | <{ a1 ≤ a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ if n1 <=? n2 then <{ true }> else <{ false }>
      | (a1', a2') ⇒ <{ a1' ≤ a2' }>
      end
  | <{ a1 > a2 }> ⇒
      match (pe_aexp pe_st a1, pe_aexp pe_st a2) with
      | (ANum n1, ANum n2) ⇒ if n1 <=? n2 then <{ false }> else <{ true }>
      | (a1', a2') ⇒ <{ a1' > a2' }>
      end
  | <{ ¬ b1 }> ⇒
      match (pe_bexp pe_st b1) with
      | <{ true }> ⇒ <{ false }>
      | <{ false }> ⇒ <{ true }>
      | b1' ⇒ <{ ¬ b1' }>
      end
  | <{ b1 && b2 }> ⇒
      match (pe_bexp pe_st b1, pe_bexp pe_st b2) with
      | (<{ true }>, <{ true }>) ⇒ <{ true }>
      | (<{ true }>, <{ false }>) ⇒ <{ false }>
      | (<{ false }>, <{ true }>) ⇒ <{ false }>
      | (<{ false }>, <{ false }>) ⇒ <{ false }>
      | (b1', b2') ⇒ <{ b1' && b2' }>
      end
  end.

Example test_pe_bexp1:
  pe_bexp [(X,3)] <{¬(X ≤ 3)}>
  = <{ false }>.
Proof. reflexivity. Qed.

Example test_pe_bexp2: ∀ b:bexp,
  b = <{ ¬(X ≤ (X + 1)) }> →
  pe_bexp [] b = b.
Proof. intros b H. rewrite → H. reflexivity. Qed.
pe_bexp 的正确性与上面 pe_aexp 的正确性类似。
Theorem pe_bexp_correct: ∀ (pe_st:pe_state) (b:bexp) (st:state),
  beval (pe_update st pe_st) b = beval st (pe_bexp pe_st b).
Proof.
  intros pe_st b st.
  induction b; simpl;
    try reflexivity;
    try (remember (pe_aexp pe_st a1) as a1';
         remember (pe_aexp pe_st a2) as a2';
         assert (H1: aeval (pe_update st pe_st) a1 = aeval st a1');
         assert (H2: aeval (pe_update st pe_st) a2 = aeval st a2');
           try (subst; apply pe_aexp_correct);
         destruct a1'; destruct a2'; rewrite H1; rewrite H2;
         simpl; try destruct (n =? n0);
         try destruct (n <=? n0); reflexivity);
    try (destruct (pe_bexp pe_st b); rewrite IHb; reflexivity);
    try (destruct (pe_bexp pe_st b1);
         destruct (pe_bexp pe_st b2);
         rewrite IHb1; rewrite IHb2; reflexivity).
Qed.

无循环命令的部分求值

那命令的部分求值呢? 部分求值与完全求值的类比继续成立。 完全求值把初始状态变成最终状态; 部分求值把初始部分状态变成最终部分状态。 区别在于状态是部分的, 命令的某些部分在静态阶段可能无法执行。 正如 pe_aexp 返回剩余 aexp、 pe_bexp 返回剩余 bexp, 对命令做部分求值会产生剩余命令。
部分求值器与完全求值器还有一处相似: 它并不对所有命令都停机。 构造一个对所有命令都停机的部分求值器并不难。 难的是构造一个既对所有命令都停机、 又自动执行所需优化(如循环展开)的求值器。 通常,换一种方式书写源程序, 让静态与动态信息的分界更明显, 就能诱使求值器更常停机并做更多优化。 这种诱导就是【绑定时间改进|Binding-Time Improvement】的艺术。 变量的绑定时间说明它的值何时已知,即「静态」还是「动态」。
目前先接受这一事实: 部分求值器并非从源命令与初始部分状态 到剩余命令与最终部分状态的全函数。 为对这种非终止建模,与命令的完全求值一样, 我们使用归纳定义的关系。我们写
      c1 / st ==> c1' / st' 表示在初始部分状态 st 中对源命令 c1 做部分求值, 得到剩余命令 c1' 与最终部分状态 st'。 例如,我们希望类似
      [] / (X := 3 ; Y := Z × (X + X)) ==> (Y := Z × 6) / [(X,3)] 的式子成立。对 X 的赋值出现在最终部分状态中, 而非剩余命令中。
(写成 st =[ c1 ]=> c1' / st' 之类会更接近 Imp 中使用的记法;也许该改一改!)

【赋值|Assignment】

首先考虑如何对赋值做部分求值。 上面源程序中的两个赋值需要区别对待。 第一个赋值 X := 3 是【静态】的。 其右部是常量(更一般地,可化简为常量)。 因此应把部分状态中 X 更新为 3, 且不产生剩余代码。(实际上会产生剩余 skip。) 第二个赋值 Y := Z × (X + X) 是【动态】的。 其右部不能化简为常量。 因此应把它留在剩余代码中, 并从部分状态中移除 Y(若在其中)。 为实现这两种情形,我们定义函数 pe_add 与 pe_remove。 与上面的 pe_update 一样,这些函数操作表示 pe_state 的 具体 list,但定理 pe_add_correct 与 pe_remove_correct 通过 pe_lookup 对 pe_state 的解释来指定它们的行为。
Fixpoint pe_remove (pe_st:pe_state) (V:string) : pe_state :=
  match pe_st with
  | [] ⇒ []
  | (V',n')::pe_st ⇒ if String.eqb V V' then pe_remove pe_st V
                      else (V',n') :: pe_remove pe_st V
  end.

Theorem pe_remove_correct: ∀ pe_st V V0,
  pe_lookup (pe_remove pe_st V) V0
  = if String.eqb V V0 then None else pe_lookup pe_st V0.
Proof. intros pe_st V V0. induction pe_st as [| [V' n'] pe_st].
  - (*  *) destruct (String.eqb V V0); reflexivity.
  - (* :: *) simpl. compare V V'.
    + (* 相等 *) rewrite IHpe_st.
      destruct (String.eqb_spec V V0). reflexivity.
      rewrite false_eqb_string; auto.
    + (* 不相等 *) simpl. compare V0 V'.
      × (* 相等 *) rewrite false_eqb_string; auto.
      × (* 不相等 *) rewrite IHpe_st. reflexivity.
Qed.

Definition pe_add (pe_st:pe_state) (V:string) (n:nat) : pe_state :=
  (V,n) :: pe_remove pe_st V.

Theorem pe_add_correct: ∀ pe_st V n V0,
  pe_lookup (pe_add pe_st V n) V0
  = if String.eqb V V0 then Some n else pe_lookup pe_st V0.
Proof. intros pe_st V n V0. unfold pe_add. simpl.
  compare V V0.
  - (* 相等 *) rewrite String.eqb_refl; auto.
  - (* 不相等 *) rewrite pe_remove_correct.
    repeat rewrite false_eqb_string; auto.
Qed.
我们将用下面两条定理分别表明部分求值器 正确处理动态赋值与静态赋值。
Theorem pe_update_update_remove: ∀ st pe_st V n,
  t_update (pe_update st pe_st) V n =
  pe_update (t_update st V n) (pe_remove pe_st V).
Proof. intros st pe_st V n. apply functional_extensionality.
  intros V0. unfold t_update. rewrite !pe_update_correct.
  rewrite pe_remove_correct. destruct (String.eqb V V0); reflexivity.
  Qed.

Theorem pe_update_update_add: ∀ st pe_st V n,
  t_update (pe_update st pe_st) V n =
  pe_update st (pe_add pe_st V n).
Proof. intros st pe_st V n. apply functional_extensionality. intros V0.
  unfold t_update. rewrite !pe_update_correct. rewrite pe_add_correct.
  destruct (String.eqb V V0); reflexivity. Qed.

【条件|Conditional】

比赋值更难做部分求值的是条件 if b1 then c1 else c2 end。 若 b1 化简为 BTrue 或 BFalse,那就容易: 我们知道会走哪个分支,直接走该分支即可。 若 b1 不能化简为常量, 就需要对两个分支都做部分求值。 而两个分支的最终部分状态可能不同!
下面的程序说明了这一困难:
      X := 3;
      if Y ≤ 4 then
          Y := 4;
          if X ≤ Y then Y := 999 else skip end
      else skip end
设初始部分状态为空。我们静态地不知道 Y 与 4 的比较结果, 因此必须对(外层)条件的两个分支都做部分求值。 在 then 分支上,我们知道 Y 被置为 4, 甚至可以利用这一知识稍微化简代码。 在 else 分支上,到最后我们仍不知道 Y 的确切值。 最终部分状态与剩余程序应当是什么?
处理这种动态条件的一种方法是取两个分支最终部分状态的交。 在本例中,我们取 (Y,4),(X,3) 与 (X,3) 的交, 因此整体最终部分状态是 (X,3)。 为补偿忘记 Y 是 4,我们需要在 then 分支末尾 添加赋值 Y := 4。于是,剩余程序会类似
      skip;
      if Y ≤ 4 then
          skip;
          skip;
          Y := 4
      else skip end
在 Rocq 中为这种情形编程需要若干辅助函数。 我们需要计算两个 pe_state 的交, 并把它们的差变成赋值序列。
首先,我们说明如何计算两个 pe_state 是否在给定变量上不一致。 在定理 pe_disagree_domain 中,我们证明两个 pe_state 只能在至少其中一个出现过的变量上不一致。
Definition pe_disagree_at (pe_st1 pe_st2 : pe_state) (V:string) : bool :=
  match pe_lookup pe_st1 V, pe_lookup pe_st2 V with
  | Some x, Some y ⇒ negb (x =? y)
  | None, None ⇒ false
  | _, _ ⇒ true
  end.

Theorem pe_disagree_domain: ∀ (pe_st1 pe_st2 : pe_state) (V:string),
  true = pe_disagree_at pe_st1 pe_st2 V →
  In V (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2).
Proof. unfold pe_disagree_at. intros pe_st1 pe_st2 V H.
  apply in_app_iff.
  remember (pe_lookup pe_st1 V) as lookup1.
  destruct lookup1 as [n1|]. left. apply pe_domain with n1. auto.
  remember (pe_lookup pe_st2 V) as lookup2.
  destruct lookup2 as [n2|]. right. apply pe_domain with n2. auto.
  inversion H. Qed.
我们定义 pe_compare 函数, 用来列出两个给定 pe_state 不一致的变量。 定理 pe_compare_correct 表明这个列表是精确的: 一个变量出现在列表中, 当且仅当两个 pe_state 在该变量上不一致。 此外,用 pe_unique 函数消除列表中的重复。
Fixpoint pe_unique (l : list string) : list string :=
  match l with
  | [] ⇒ []
  | x::l ⇒
      x :: filter (fun y ⇒ if String.eqb x y then false else true) (pe_unique l)
  end.

Theorem pe_unique_correct: ∀ l x,
  In x l ↔ In x (pe_unique l).
Proof. intros l x. induction l as [| h t]. reflexivity.
  simpl in ×. split.
  - (* -> *)
    intros. inversion H; clear H.
      left. assumption.
      destruct (String.eqb_spec h x).
         left. assumption.
         right. apply filter_In. split.
           apply IHt. assumption.
           rewrite false_eqb_string; auto.
  - (* <- *)
    intros. inversion H; clear H.
       left. assumption.
       apply filter_In in H0. inversion H0. right. apply IHt. assumption.
Qed.

Definition pe_compare (pe_st1 pe_st2 : pe_state) : list string :=
  pe_unique (filter (pe_disagree_at pe_st1 pe_st2)
    (map (@fst _ _) pe_st1 ++ map (@fst _ _) pe_st2)).

Theorem pe_compare_correct: ∀ pe_st1 pe_st2 V,
  pe_lookup pe_st1 V = pe_lookup pe_st2 V ↔
  ¬ In V (pe_compare pe_st1 pe_st2).
Proof. intros pe_st1 pe_st2 V.
  unfold pe_compare. rewrite <- pe_unique_correct. rewrite filter_In.
  split; intros Heq.
  - (* -> *)
    intro. destruct H. unfold pe_disagree_at in H0. rewrite Heq in H0.
    destruct (pe_lookup pe_st2 V).
    rewrite → eqb_refl in H0. inversion H0.
    inversion H0.
  - (* <- *)
    assert (Hagree: pe_disagree_at pe_st1 pe_st2 V = false).
    { (* 断言的证明 *)
      remember (pe_disagree_at pe_st1 pe_st2 V) as disagree.
      destruct disagree; [| reflexivity].
      apply pe_disagree_domain in Heqdisagree.
      exfalso. apply Heq. split. assumption. reflexivity. }
    unfold pe_disagree_at in Hagree.
    destruct (pe_lookup pe_st1 V) as [n1|];
    destruct (pe_lookup pe_st2 V) as [n2|];
      try reflexivity; try solve_by_invert.
    rewrite negb_false_iff in Hagree.
    apply eqb_eq in Hagree. subst. reflexivity. Qed.
两个部分状态的交,是从其中一个移除二者不一致的全部变量后的结果。 我们用上面的 pe_remove 定义函数 pe_removes, 以便一次移除一整列变量。
定理 pe_compare_removes 表明:无论我们从两个部分状态中的 哪一个移除变量,该交运算结果的 pe_lookup 解释都相同。 由于 pe_update 只依赖部分状态的 pe_lookup 解释, 它也不在乎从哪一个移除变量;定理 pe_compare_update 随后会用在正确性证明中。
Fixpoint pe_removes (pe_st:pe_state) (ids : list string) : pe_state :=
  match ids with
  | [] ⇒ pe_st
  | V::ids ⇒ pe_remove (pe_removes pe_st ids) V
  end.

Theorem pe_removes_correct: ∀ pe_st ids V,
  pe_lookup (pe_removes pe_st ids) V =
  if inb String.eqb V ids then None else pe_lookup pe_st V.
Proof. intros pe_st ids V. induction ids as [| V' ids]. reflexivity.
  simpl. rewrite pe_remove_correct. rewrite IHids.
  compare V' V.
  - rewrite String.eqb_refl. reflexivity.
  - rewrite false_eqb_string; try congruence. reflexivity.
Qed.

Theorem pe_compare_removes: ∀ pe_st1 pe_st2 V,
  pe_lookup (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) V =
  pe_lookup (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)) V.
Proof.
  intros pe_st1 pe_st2 V. rewrite !pe_removes_correct.
  destruct (inbP _ _ String.eqb_spec V (pe_compare pe_st1 pe_st2)).
  - reflexivity.
  - apply pe_compare_correct. auto. Qed.

Theorem pe_compare_update: ∀ pe_st1 pe_st2 st,
  pe_update st (pe_removes pe_st1 (pe_compare pe_st1 pe_st2)) =
  pe_update st (pe_removes pe_st2 (pe_compare pe_st1 pe_st2)).
Proof. intros. apply functional_extensionality. intros V.
  rewrite !pe_update_correct. rewrite pe_compare_removes. reflexivity.
Qed.
最后,我们定义 assign 函数,把两个部分状态之间的差 变成一串赋值命令。更精确地,assign pe_st ids 为 ids 中列出的每个变量生成一条赋值命令。
Fixpoint assign (pe_st : pe_state) (ids : list string) : com :=
  match ids with
  | [] ⇒ <{ skip }>
  | V::ids ⇒ match pe_lookup pe_st V with
              | Some n ⇒ <{ assign pe_st ids; V := n }>
              | None ⇒ assign pe_st ids
              end
  end.
assign 生成的命令总是终止,因为它只是一串赋值。 下面的(全)函数 assigned 计算该命令对(动态状态)的作用。 定理 assign_removes 随后确认:生成的赋值恰好补偿了 从部分状态中移除的变量。
Definition assigned (pe_st:pe_state) (ids : list string) (st:state) : state :=
  fun V ⇒ if inb String.eqb V ids then
                match pe_lookup pe_st V with
                | Some n ⇒ n
                | None ⇒ st V
                end
           else st V.

Theorem assign_removes: ∀ pe_st ids st,
  pe_update st pe_st =
  pe_update (assigned pe_st ids st) (pe_removes pe_st ids).
Proof. intros pe_st ids st. apply functional_extensionality. intros V.
  rewrite !pe_update_correct. rewrite pe_removes_correct. unfold assigned.
  destruct (inbP _ _ String.eqb_spec V ids); destruct (pe_lookup pe_st V); reflexivity.
Qed.

Lemma ceval_extensionality: ∀ c st st1 st2,
  st =[ c ]=> st1 → (∀ V, st1 V = st2 V) → st =[ c ]=> st2.
Proof. intros c st st1 st2 H Heq.
  apply functional_extensionality in Heq. rewrite <- Heq. apply H. Qed.

Theorem eval_assign: ∀ pe_st ids st,
  st =[ assign pe_st ids ]=> assigned pe_st ids st.
Proof. intros pe_st ids st. induction ids as [| V ids]; simpl.
  - (*  *) eapply ceval_extensionality. apply E_Skip. reflexivity.
  - (* V::ids *)
    remember (pe_lookup pe_st V) as lookup. destruct lookup.
    + (* Some *) eapply E_Seq. apply IHids. unfold assigned. simpl.
      eapply ceval_extensionality. apply E_Asgn. simpl. reflexivity.
      intros V0. unfold t_update. compare V V0.
      × (* 相等 *) rewrite <- Heqlookup. rewrite String.eqb_refl. reflexivity.
      × (* 不相等 *) rewrite false_eqb_string; simpl; congruence.
    + (* None *) eapply ceval_extensionality. apply IHids.
      unfold assigned. intros V0. simpl. compare V V0.
      × (* 相等 *) rewrite <- Heqlookup.
        rewrite String.eqb_refl.
        destruct (inbP _ _ String.eqb_spec V ids); reflexivity.
      × (* 不相等 *) rewrite false_eqb_string; simpl; congruence.
Qed.

【部分求值关系|Partial Evaluation Relation】

终于,我们可以把无循环命令的部分求值器定义为归纳关系了! PE_AsgnDynamic 与 PE_If 中的不等式条件只是为了 保持部分求值器的确定性;正确性并不需要它们。

Inductive pe_com : com → pe_state → com → pe_state → Prop :=
  | PE_Skip : ∀ pe_st,
      <{skip}> / pe_st ==> <{skip}> / pe_st
  | PE_AsgnStatic : ∀ pe_st a1 (n1 : nat) l,
      pe_aexp pe_st a1 = <{ n1 }> →
      <{l := a1}> / pe_st ==> <{skip}> / pe_add pe_st l n1
  | PE_AsgnDynamic : ∀ pe_st a1 a1' l,
      pe_aexp pe_st a1 = a1' →
      (∀ n : nat , a1' ≠ <{ n }>) →
      <{l := a1}> / pe_st ==> <{l := a1'}> / pe_remove pe_st l
  | PE_Seq : ∀ pe_st pe_st' pe_st'' c1 c2 c1' c2',
      c1 / pe_st ==> c1' / pe_st' →
      c2 / pe_st' ==> c2' / pe_st'' →
      <{c1 ; c2}> / pe_st ==> <{c1' ; c2'}> / pe_st''
  | PE_IfTrue : ∀ pe_st pe_st' b1 c1 c2 c1',
      pe_bexp pe_st b1 = <{ true }> →
      c1 / pe_st ==> c1' / pe_st' →
      <{if b1 then c1 else c2 end}> / pe_st ==> c1' / pe_st'
  | PE_IfFalse : ∀ pe_st pe_st' b1 c1 c2 c2',
      pe_bexp pe_st b1 = <{ false }> →
      c2 / pe_st ==> c2' / pe_st' →
      <{if b1 then c1 else c2 end}> / pe_st ==> c2' / pe_st'
  | PE_If : ∀ pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2',
      pe_bexp pe_st b1 ≠ <{ true }> →
      pe_bexp pe_st b1 ≠ <{ false }> →
      c1 / pe_st ==> c1' / pe_st1 →
      c2 / pe_st ==> c2' / pe_st2 →
      <{if b1 then c1 else c2 end}> / pe_st
        ==> <{if pe_bexp pe_st b1
             then c1' ; assign pe_st1 (pe_compare pe_st1 pe_st2)
             else c2' ; assign pe_st2 (pe_compare pe_st1 pe_st2) end}>
            / pe_removes pe_st1 (pe_compare pe_st1 pe_st2)

  where "c1 '/' st '==>' c1' '/' st'" := (pe_com c1 st c1' st').

Local Hint Constructors pe_com : core.
Local Hint Constructors ceval : core.

【示例|Example】

下面是一些使用部分求值器的示例。 要让 pe_com 关系真正可用于自动部分求值, 我们需要在 Rocq 中定义更多自动化策略。 这不难做,但这里不需要。
Example pe_example1:
  <{X := 3 ; Y := Z × (X + X)}>
  / [] ==> <{skip; Y := Z × 6}> / [(X,3)].
Proof. eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  eapply PE_AsgnDynamic. reflexivity. intros n H. inversion H. Qed.

Example pe_example2:
  <{X := 3 ; if X ≤ 4 then X := 4 else skip end}>
  / [] ==> <{skip; skip}> / [(X,4)].
Proof. eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  eapply PE_IfTrue. reflexivity.
  eapply PE_AsgnStatic. reflexivity. Qed.

Example pe_example3:
  <{X := 3;
   if Y ≤ 4 then
     Y := 4;
     if X = Y then Y := 999 else skip end
   else skip end}> / []
  ==> <{skip;
       if Y ≤ 4 then
         (skip; skip); (skip; Y := 4)
       else skip; skip end}>
      / [(X,3)].
Proof. erewrite f_equal2 with (f := fun c st ⇒ _ / _ ==> c / st).
  eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  eapply PE_If; intuition eauto; try solve_by_invert.
  econstructor. eapply PE_AsgnStatic. reflexivity.
  eapply PE_IfFalse. reflexivity. econstructor.
  reflexivity. reflexivity. Qed.

部分求值的正确性

最后,让我们证明这个部分求值器是正确的!

Inductive pe_ceval
  (c':com) (pe_st':pe_state) (st:state) (st'':state) : Prop :=
  | pe_ceval_intro : ∀ st',
    st =[ c' ]=> st' →
    pe_update st' pe_st' = st'' →
    c' / pe_st' / st ==> st''
  where "c' '/' pe_st' '/' st '==>' st''" := (pe_ceval c' pe_st' st st'').

Local Hint Constructors pe_ceval : core.

Theorem pe_com_complete:
  ∀ c pe_st pe_st' c', c / pe_st ==> c' / pe_st' →
  ∀ st st'',
  (pe_update st pe_st =[ c ]=> st'') →
  (c' / pe_st' / st ==> st'').
Proof. intros c pe_st pe_st' c' Hpe.
  induction Hpe; intros st st'' Heval;
  try (inversion Heval; subst;
       try (rewrite → pe_bexp_correct, → H in *; solve_by_invert);
       []);
  eauto.
  - (* PE_AsgnStatic *) econstructor. econstructor.
    rewrite → pe_aexp_correct. rewrite <- pe_update_update_add.
    rewrite → H. reflexivity.
  - (* PE_AsgnDynamic *) econstructor. econstructor. reflexivity.
    rewrite → pe_aexp_correct. rewrite <- pe_update_update_remove.
    reflexivity.
  - (* PE_Seq *)
    edestruct IHHpe1. eassumption. subst.
    edestruct IHHpe2. eassumption.
    eauto.
  - (* PE_If *) inversion Heval; subst.
    + (* E'IfTrue *) edestruct IHHpe1. eassumption.
      econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption.
      eapply E_Seq. eassumption. apply eval_assign.
      rewrite <- assign_removes. eassumption.
    + (* E_IfFalse *) edestruct IHHpe2. eassumption.
      econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption.
      eapply E_Seq. eassumption. apply eval_assign.
      rewrite → pe_compare_update.
      rewrite <- assign_removes. eassumption.
Qed.

Theorem pe_com_sound:
  ∀ c pe_st pe_st' c', c / pe_st ==> c' / pe_st' →
  ∀ st st'',
  (c' / pe_st' / st ==> st'') →
  (pe_update st pe_st =[ c ]=> st'').
Proof. intros c pe_st pe_st' c' Hpe.
  induction Hpe;
    intros st st'' [st' Heval Heq];
    try (inversion Heval; []; subst); auto.
  - (* PE_AsgnStatic *) rewrite <- pe_update_update_add. apply E_Asgn.
    rewrite → pe_aexp_correct. rewrite → H. reflexivity.
  - (* PE_AsgnDynamic *) rewrite <- pe_update_update_remove. apply E_Asgn.
    rewrite <- pe_aexp_correct. reflexivity.
  - (* PE_Seq *) eapply E_Seq; eauto.
  - (* PE_IfTrue *) apply E_IfTrue.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity. eauto.
  - (* PE_IfFalse *) apply E_IfFalse.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity. eauto.
  - (* PE_If *)
    inversion Heval; subst; inversion H7;
      (eapply ceval_deterministic in H8; [| apply eval_assign]); subst.
    + (* E_IfTrue *)
      apply E_IfTrue. rewrite → pe_bexp_correct. assumption.
      rewrite <- assign_removes. eauto.
    + (* E_IfFalse *)
      rewrite → pe_compare_update.
      apply E_IfFalse. rewrite → pe_bexp_correct. assumption.
      rewrite <- assign_removes. eauto.
Qed.
主定理。感谢 David Menendez 给出这一表述!
Corollary pe_com_correct:
  ∀ c pe_st pe_st' c', c / pe_st ==> c' / pe_st' →
  ∀ st st'',
  (pe_update st pe_st =[ c ]=> st'') ↔
  (c' / pe_st' / st ==> st'').
Proof. intros c pe_st pe_st' c' H st st''. split.
  - (* -> *) apply pe_com_complete. apply H.
  - (* <- *) apply pe_com_sound. apply H.
Qed.

循环的部分求值

初看起来,把上面的部分求值关系 pe_com 扩展到循环似乎很直接。 确实,许多循环容易处理。比如考虑下面反复平方的循环:
      while 1 ≤ X do
          Y := Y × Y;
          X := X - 1
      end
若静态地既不知道 X 也不知道 Y, 则整个循环是动态的,剩余命令应与之相同。 若知道 X 但不知道 Y,循环可以一路展开。 例如当 X 初始为 3(最终为 0)时, 剩余命令应是
      Y := Y × Y;
      Y := Y × Y;
      Y := Y × Y
一般地,若循环体的最终部分状态等于初始状态, 或守卫条件是静态的, 则该循环容易做部分求值。
但还有另一些循环,我们很难在 Imp 中表达出所需的剩余程序。 例如,取下面检查 Y 是偶还是奇的程序:
      X := 0;
      while 1 ≤ Y do
          Y := Y - 1 ;
          X := 1 - X
      end
在循环过程中 X 的值在 0 与 1 之间交替。 理想情况下,我们希望把这个循环展开(不是一路,而是)【两次】, 得到类似
      while 1 ≤ Y do
          Y := Y - 1;
          if 1 ≤ Y then
              Y := Y - 1
          else
              X := 1; EXIT
          end
      end;
      X := 0
的程序。不幸的是,Imp 中没有 EXIT 命令。 不扩展语言可用控制结构的话, 最多只能重复循环守卫测试或添加标志变量。 两者都不太理想。
不过,作为离题,下面是对 Imp 命令做部分求值的一次尝试。 我们给 pe_com 关系再加一个命令参数 c'', 用来记录一个待收卷的循环。
Module Loop.


Inductive pe_com : com → pe_state → com → pe_state → com → Prop :=
  | PE_Skip : ∀ pe_st,
      <{ skip }> / pe_st ==> <{ skip }> / pe_st / <{skip}>
  | PE_AsgnStatic : ∀ pe_st a1 (n1 : nat) l,
      pe_aexp pe_st a1 = <{ n1 }> →
      <{ l := a1 }> / pe_st ==> <{ skip }> / pe_add pe_st l n1 / <{skip}>
  | PE_AsgnDynamic : ∀ pe_st a1 a1' l,
      pe_aexp pe_st a1 = a1' →
      (∀ n : nat, a1' ≠ <{ n }> ) →
      <{l := a1}> / pe_st ==> <{l := a1'}> / pe_remove pe_st l / <{skip}>
  | PE_Seq : ∀ pe_st pe_st' pe_st'' c1 c2 c1' c2' c'',
      c1 / pe_st ==> c1' / pe_st' / <{skip}> →
      c2 / pe_st' ==> c2' / pe_st'' / c'' →
      <{c1 ; c2}> / pe_st ==> <{c1' ; c2'}> / pe_st'' / c''
  | PE_IfTrue : ∀ pe_st pe_st' b1 c1 c2 c1' c'',
      pe_bexp pe_st b1 = <{ true }> →
      c1 / pe_st ==> c1' / pe_st' / c'' →
      <{if b1 then c1 else c2 end}> / pe_st ==> c1' / pe_st' / c''
  | PE_IfFalse : ∀ pe_st pe_st' b1 c1 c2 c2' c'',
      pe_bexp pe_st b1 = <{ false }> →
      c2 / pe_st ==> c2' / pe_st' / c'' →
      <{if b1 then c1 else c2 end}> / pe_st ==> c2' / pe_st' / c''
  | PE_If : ∀ pe_st pe_st1 pe_st2 b1 c1 c2 c1' c2' c'',
      pe_bexp pe_st b1 ≠ <{ true }> →
      pe_bexp pe_st b1 ≠ <{ false }> →
      c1 / pe_st ==> c1' / pe_st1 / c'' →
      c2 / pe_st ==> c2' / pe_st2 / c'' →
      <{if b1 then c1 else c2 end}> / pe_st
        ==> <{if pe_bexp pe_st b1
             then c1' ; assign pe_st1 (pe_compare pe_st1 pe_st2)
             else c2' ; assign pe_st2 (pe_compare pe_st1 pe_st2) end}>
            / pe_removes pe_st1 (pe_compare pe_st1 pe_st2)
            / c''
  | PE_WhileFalse : ∀ pe_st b1 c1,
      pe_bexp pe_st b1 = <{ false }> →
      <{while b1 do c1 end}> / pe_st ==> <{skip}> / pe_st / <{skip}>
  | PE_WhileTrue : ∀ pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'',
      pe_bexp pe_st b1 = <{ true }> →
      c1 / pe_st ==> c1' / pe_st' / <{skip}> →
      <{while b1 do c1 end}> / pe_st' ==> c2' / pe_st'' / c2'' →
      pe_compare pe_st pe_st'' ≠ [] →
      <{while b1 do c1 end}> / pe_st ==> <{c1';c2'}> / pe_st'' / c2''
  | PE_While : ∀ pe_st pe_st' pe_st'' b1 c1 c1' c2' c2'',
      pe_bexp pe_st b1 ≠ <{ false }> →
      pe_bexp pe_st b1 ≠ <{ true }> →
      c1 / pe_st ==> c1' / pe_st' / <{skip}> →
      <{while b1 do c1 end}> / pe_st' ==> c2' / pe_st'' / c2'' →
      pe_compare pe_st pe_st'' ≠ [] →
      (c2'' = <{skip}> ∨ c2'' = <{while b1 do c1 end}>) →
      <{while b1 do c1 end}> / pe_st
        ==> <{if pe_bexp pe_st b1
             then c1'; c2'; assign pe_st'' (pe_compare pe_st pe_st'')
             else assign pe_st (pe_compare pe_st pe_st'') end}>
            / pe_removes pe_st (pe_compare pe_st pe_st'')
            / c2''
  | PE_WhileFixedEnd : ∀ pe_st b1 c1,
      pe_bexp pe_st b1 ≠ <{ false }> →
      <{while b1 do c1 end}> / pe_st ==> <{skip}> / pe_st / <{while b1 do c1 end}>
  | PE_WhileFixedLoop : ∀ pe_st pe_st' pe_st'' b1 c1 c1' c2',
      pe_bexp pe_st b1 = <{ true }> →
      c1 / pe_st ==> c1' / pe_st' / <{skip}> →
      <{while b1 do c1 end}> / pe_st'
        ==> c2' / pe_st'' / <{while b1 do c1 end}>→
      pe_compare pe_st pe_st'' = [] →
      <{while b1 do c1 end}> / pe_st
        ==> <{while true do skip end}> / pe_st / <{skip}>
      (* 因为这里是无限循环,我们实际上应开始丢弃程序的其余部分:
         (while b1 do c1 end) / pe_st
         ==> skip / pe_st / (while true do skip end) *)

  | PE_WhileFixed : ∀ pe_st pe_st' pe_st'' b1 c1 c1' c2',
      pe_bexp pe_st b1 ≠ <{ false }> →
      pe_bexp pe_st b1 ≠ <{ true }> →
      c1 / pe_st ==> c1' / pe_st' / <{skip}> →
      <{while b1 do c1 end}> / pe_st'
        ==> c2' / pe_st'' / <{while b1 do c1 end}> →
      pe_compare pe_st pe_st'' = [] →
      <{while b1 do c1 end}> / pe_st
        ==> <{while pe_bexp pe_st b1 do c1'; c2' end}> / pe_st / <{skip}>

  where "c1 '/' st '==>' c1' '/' st' '/' c''" := (pe_com c1 st c1' st' c'').

Local Hint Constructors pe_com : core.

【示例|Example】

Ltac step i :=
  (eapply i; intuition eauto; try solve_by_invert);
  repeat (try eapply PE_Seq;
          try (eapply PE_AsgnStatic; simpl; reflexivity);
          try (eapply PE_AsgnDynamic;
               [ simpl; reflexivity
               | intuition eauto; solve_by_invert])).

Definition square_loop: com :=
  <{while 1 ≤ X do
    Y := Y × Y;
    X := X - 1
  end}>.

Example pe_loop_example1:
  square_loop / []
  ==> <{while 1 ≤ X do
         (Y := Y × Y;
          X := X - 1); skip
       end}> / [] / <{skip}>.
Proof. erewrite f_equal2 with (f := fun c st ⇒ _ / _ ==> c / st / <{skip}>).
  step PE_WhileFixed. step PE_WhileFixedEnd. reflexivity.
  reflexivity. reflexivity. Qed.

Example pe_loop_example2:
  <{X := 3; square_loop}> / []
  ==> <{skip;
       (Y := Y × Y; skip);
       (Y := Y × Y; skip);
       (Y := Y × Y; skip);
       skip}> / [(X,0)] / <{skip}>.
Proof. erewrite f_equal2 with (f := fun c st ⇒ _ / _ ==> c / st / <{skip}>).
  eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  step PE_WhileTrue.
  step PE_WhileTrue.
  step PE_WhileTrue.
  step PE_WhileFalse.
  inversion H. inversion H. inversion H.
  reflexivity. reflexivity. Qed.

Example pe_loop_example3:
  <{Z := 3; subtract_slowly}> / []
  ==> <{skip;
       if X ≠ 0 then
         (skip; X := X - 1);
         if X ≠ 0 then
           (skip; X := X - 1);
           if X ≠ 0 then
             (skip; X := X - 1);
             while X ≠ 0 do
               (skip; X := X - 1); skip
             end;
             skip; Z := 0
           else skip; Z := 1 end; skip
         else skip; Z := 2 end; skip
       else skip; Z := 3 end}> / [] / <{skip}>.
Proof. erewrite f_equal2 with (f := fun c st ⇒ _ / _ ==> c / st / <{skip}>).
  eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  step PE_While.
  step PE_While.
  step PE_While.
  step PE_WhileFixed.
  step PE_WhileFixedEnd.
  reflexivity. inversion H. inversion H. inversion H.
  reflexivity. reflexivity. Qed.

Example pe_loop_example4:
  <{X := 0;
   while X ≤ 2 do
     X := 1 - X
   end}> / [] ==> <{skip; while true do skip end}> / [(X,0)] / <{skip}>.
Proof. erewrite f_equal2 with (f := fun c st ⇒ _ / _ ==> c / st / <{skip}>).
  eapply PE_Seq. eapply PE_AsgnStatic. reflexivity.
  step PE_WhileFixedLoop.
  step PE_WhileTrue.
  step PE_WhileFixedEnd.
  inversion H. reflexivity. reflexivity. reflexivity. Qed.

【正确性|Correctness】

该部分求值器能把循环展开 n 次, 其中 n 是大于一的(有限)整数。 为证明其正确性, 归纳应对动态求值进入循环体的次数进行, 而非对动态求值作结构归纳。

Inductive ceval_count : com → state → state → nat → Prop :=
  | E'Skip : ∀ st,
      <{skip}> / st ==> st # 0
  | E'Asgn : ∀ st a1 n l,
      aeval st a1 = n →
      <{l := a1}> / st ==> (t_update st l n) # 0
  | E'Seq : ∀ c1 c2 st st' st'' n1 n2,
      c1 / st ==> st' # n1 →
      c2 / st' ==> st'' # n2 →
      <{c1 ; c2}> / st ==> st'' # (n1 + n2)
  | E'IfTrue : ∀ st st' b1 c1 c2 n,
      beval st b1 = true →
      c1 / st ==> st' # n →
      <{if b1 then c1 else c2 end}> / st ==> st' # n
  | E'IfFalse : ∀ st st' b1 c1 c2 n,
      beval st b1 = false →
      c2 / st ==> st' # n →
      <{if b1 then c1 else c2 end}> / st ==> st' # n
  | E'WhileFalse : ∀ b1 st c1,
      beval st b1 = false →
      <{while b1 do c1 end}> / st ==> st # 0
  | E'WhileTrue : ∀ st st' st'' b1 c1 n1 n2,
      beval st b1 = true →
      c1 / st ==> st' # n1 →
      <{while b1 do c1 end}> / st' ==> st'' # n2 →
      <{while b1 do c1 end}> / st ==> st'' # S (n1 + n2)

  where "c1 '/' st '==>' st' # n" := (ceval_count c1 st st' n).

Local Hint Constructors ceval_count : core.

Theorem ceval_count_complete: ∀ c st st',
  st =[ c ]=> st' → ∃ n, c / st ==> st' # n.
Proof. intros c st st' Heval.
  induction Heval;
    try inversion IHHeval1;
    try inversion IHHeval2;
    try inversion IHHeval;
    eauto. Qed.

Theorem ceval_count_sound: ∀ c st st' n,
  c / st ==> st' # n → st =[ c ]=> st'.
Proof. intros c st st' n Heval. induction Heval; eauto. Qed.

Theorem pe_compare_nil_lookup: ∀ pe_st1 pe_st2,
  pe_compare pe_st1 pe_st2 = [] →
  ∀ V, pe_lookup pe_st1 V = pe_lookup pe_st2 V.
Proof. intros pe_st1 pe_st2 H V.
  apply (pe_compare_correct pe_st1 pe_st2 V).
  rewrite H. intro. inversion H0. Qed.

Theorem pe_compare_nil_update: ∀ pe_st1 pe_st2,
  pe_compare pe_st1 pe_st2 = [] →
  ∀ st, pe_update st pe_st1 = pe_update st pe_st2.
Proof. intros pe_st1 pe_st2 H st.
  apply functional_extensionality. intros V.
  rewrite !pe_update_correct.
  apply pe_compare_nil_lookup with (V:=V) in H.
  rewrite H. reflexivity. Qed.


Inductive pe_ceval_count (c':com) (pe_st':pe_state) (c'':com)
                         (st:state) (st'':state) (n:nat) : Prop :=
  | pe_ceval_count_intro : ∀ st' n',
    st =[ c' ]=> st' →
    c'' / pe_update st' pe_st' ==> st'' # n' →
    n' ≤ n →
    c' / pe_st' / c'' / st ==> st'' # n
  where "c' '/' pe_st' '/' c'' '/' st '==>' st'' '#' n" :=
        (pe_ceval_count c' pe_st' c'' st st'' n).

Local Hint Constructors pe_ceval_count : core.

Lemma pe_ceval_count_le: ∀ c' pe_st' c'' st st'' n n',
  n' ≤ n →
  c' / pe_st' / c'' / st ==> st'' # n' →
  c' / pe_st' / c'' / st ==> st'' # n.
Proof. intros c' pe_st' c'' st st'' n n' Hle H. inversion H.
  econstructor; try eassumption. lia. Qed.

Theorem pe_com_complete:
  ∀ c pe_st pe_st' c' c'', c / pe_st ==> c' / pe_st' / c'' →
  ∀ st st'' n,
  (c / pe_update st pe_st ==> st'' # n) →
  (c' / pe_st' / c'' / st ==> st'' # n).
Proof. intros c pe_st pe_st' c' c'' Hpe.
  induction Hpe; intros st st'' n Heval;
  try (inversion Heval; subst;
       try (rewrite → pe_bexp_correct, → H in *; solve_by_invert);
       []);
  eauto.
  - (* PE_AsgnStatic *) econstructor. econstructor.
    rewrite → pe_aexp_correct. rewrite <- pe_update_update_add.
    rewrite → H. apply E'Skip. auto.
  - (* PE_AsgnDynamic *) econstructor. econstructor. reflexivity.
    rewrite → pe_aexp_correct. rewrite <- pe_update_update_remove.
    apply E'Skip. auto.
  - (* PE_Seq *)
    edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption.
    inversion Hskip. subst.
    edestruct IHHpe2. eassumption.
    econstructor; eauto. lia.
  - (* PE_If *) inversion Heval; subst.
    + (* E'IfTrue *) edestruct IHHpe1. eassumption.
      econstructor. apply E_IfTrue. rewrite <- pe_bexp_correct. assumption.
      eapply E_Seq. eassumption. apply eval_assign.
      rewrite <- assign_removes. eassumption. eassumption.
    + (* E_IfFalse *) edestruct IHHpe2. eassumption.
      econstructor. apply E_IfFalse. rewrite <- pe_bexp_correct. assumption.
      eapply E_Seq. eassumption. apply eval_assign.
      rewrite → pe_compare_update.
      rewrite <- assign_removes. eassumption. eassumption.
  - (* PE_WhileTrue *)
    edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption.
    inversion Hskip. subst.
    edestruct IHHpe2. eassumption.
    econstructor; eauto. lia.
  - (* PE_While *) inversion Heval; subst.
    + (* E_WhileFalse *) econstructor. apply E_IfFalse.
      rewrite <- pe_bexp_correct. assumption.
      apply eval_assign.
      rewrite <- assign_removes. inversion H2; subst; auto.
      auto.
    + (* E_WhileTrue *)
      edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption.
      inversion Hskip. subst.
      edestruct IHHpe2. eassumption.
      econstructor. apply E_IfTrue.
      rewrite <- pe_bexp_correct. assumption.
      repeat eapply E_Seq; eauto. apply eval_assign.
      rewrite → pe_compare_update, <- assign_removes. eassumption.
      lia.
  - (* PE_WhileFixedLoop *) exfalso.
    generalize dependent (S (n1 + n2)). intros n.
    clear - H H0 IHHpe1 IHHpe2. generalize dependent st.
    induction n using lt_wf_ind; intros st Heval. inversion Heval; subst.
    + (* E'WhileFalse *) rewrite pe_bexp_correct, H in H7. inversion H7.
    + (* E'WhileTrue *)
      edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption.
      inversion Hskip. subst.
      edestruct IHHpe2. eassumption.
      rewrite <- (pe_compare_nil_update _ _ H0) in H7.
      apply H1 in H7; [| lia]. inversion H7.
  - (* PE_WhileFixed *) generalize dependent st.
    induction n using lt_wf_ind; intros st Heval. inversion Heval; subst.
    + (* E'WhileFalse *) rewrite pe_bexp_correct in H8. eauto.
    + (* E'WhileTrue *) rewrite pe_bexp_correct in H5.
      edestruct IHHpe1 as [? ? ? Hskip ?]. eassumption.
      inversion Hskip. subst.
      edestruct IHHpe2. eassumption.
      rewrite <- (pe_compare_nil_update _ _ H1) in H8.
      apply H2 in H8; [| lia]. inversion H8.
      econstructor; [ eapply E_WhileTrue; eauto | eassumption | lia].
Qed.

Theorem pe_com_sound:
  ∀ c pe_st pe_st' c' c'', c / pe_st ==> c' / pe_st' / c'' →
  ∀ st st'' n,
  (c' / pe_st' / c'' / st ==> st'' # n) →
  (pe_update st pe_st =[ c ]=> st'').
Proof. intros c pe_st pe_st' c' c'' Hpe.
  induction Hpe;
    intros st st'' n [st' n' Heval Heval' Hle];
    try (inversion Heval; []; subst);
    try (inversion Heval'; []; subst); eauto.
  - (* PE_AsgnStatic *) rewrite <- pe_update_update_add. apply E_Asgn.
    rewrite → pe_aexp_correct. rewrite → H. reflexivity.
  - (* PE_AsgnDynamic *) rewrite <- pe_update_update_remove. apply E_Asgn.
    rewrite <- pe_aexp_correct. reflexivity.
  - (* PE_Seq *) eapply E_Seq; eauto.
  - (* PE_IfTrue *) apply E_IfTrue.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity.
    eapply IHHpe. eauto.
  - (* PE_IfFalse *) apply E_IfFalse.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity.
    eapply IHHpe. eauto.
  - (* PE_If *) inversion Heval; subst; inversion H7; subst; clear H7.
    + (* E_IfTrue *)
      eapply ceval_deterministic in H8; [| apply eval_assign]. subst.
      rewrite <- assign_removes in Heval'.
      apply E_IfTrue. rewrite → pe_bexp_correct. assumption.
      eapply IHHpe1. eauto.
    + (* E_IfFalse *)
      eapply ceval_deterministic in H8; [| apply eval_assign]. subst.
      rewrite → pe_compare_update in Heval'.
      rewrite <- assign_removes in Heval'.
      apply E_IfFalse. rewrite → pe_bexp_correct. assumption.
      eapply IHHpe2. eauto.
  - (* PE_WhileFalse *) apply E_WhileFalse.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity.
  - (* PE_WhileTrue *) eapply E_WhileTrue.
    rewrite → pe_bexp_correct. rewrite → H. reflexivity.
    eapply IHHpe1. eauto. eapply IHHpe2. eauto.
  - (* PE_While *) inversion Heval; subst.
    + (* E_IfTrue *)
      inversion H9. subst. clear H9.
      inversion H10. subst. clear H10.
      eapply ceval_deterministic in H11; [| apply eval_assign]. subst.
      rewrite → pe_compare_update in Heval'.
      rewrite <- assign_removes in Heval'.
      eapply E_WhileTrue. rewrite → pe_bexp_correct. assumption.
      eapply IHHpe1. eauto.
      eapply IHHpe2. eauto.
    + (* E_IfFalse *) apply ceval_count_sound in Heval'.
      eapply ceval_deterministic in H9; [| apply eval_assign]. subst.
      rewrite <- assign_removes in Heval'.
      inversion H2; subst.
      × (* c2'' = skip *) inversion Heval'. subst. apply E_WhileFalse.
        rewrite → pe_bexp_correct. assumption.
      × (* c2'' = while b1 do c1 end *) assumption.
  - (* PE_WhileFixedEnd *) eapply ceval_count_sound. apply Heval'.
  - (* PE_WhileFixedLoop *)
    apply loop_never_stops in Heval. inversion Heval.
  - (* PE_WhileFixed *)
    clear - H1 IHHpe1 IHHpe2 Heval.
    remember <{while pe_bexp pe_st b1 do c1'; c2' end}> as c'.
    induction Heval;
      inversion Heqc'; subst; clear Heqc'.
    + (* E_WhileFalse *) apply E_WhileFalse.
      rewrite pe_bexp_correct. assumption.
    + (* E_WhileTrue *)
      assert (IHHeval2' := IHHeval2 (refl_equal _)).
      apply ceval_count_complete in IHHeval2'. inversion IHHeval2'.
      clear IHHeval1 IHHeval2 IHHeval2'.
      inversion Heval1. subst.
      eapply E_WhileTrue. rewrite pe_bexp_correct. assumption. eauto.
      eapply IHHpe2. econstructor. eassumption.
      rewrite <- (pe_compare_nil_update _ _ H1). eassumption. apply le_n.
Qed.

Corollary pe_com_correct:
  ∀ c pe_st pe_st' c', c / pe_st ==> c' / pe_st' / <{skip}> →
  ∀ st st'',
  (pe_update st pe_st =[ c ]=> st'') ↔
  (∃ st', st =[ c' ]=> st' ∧ pe_update st' pe_st' = st'').
Proof. intros c pe_st pe_st' c' H st st''. split.
  - (* -> *) intros Heval.
    apply ceval_count_complete in Heval. inversion Heval as [n Heval'].
    apply pe_com_complete with (st:=st) (st'':=st'') (n:=n) in H.
    inversion H as [? ? ? Hskip ?]. inversion Hskip. subst. eauto.
    assumption.
  - (* <- *) intros [st' [Heval Heq] ]. subst st''.
    eapply pe_com_sound in H. apply H.
    econstructor. apply Heval. apply E'Skip. apply le_n.
Qed.

End Loop.

流程图程序的部分求值

除了直接对 while 循环做部分求值, 标准做法是把命令式程序转换成【流程图】。 给语言加上标签与跳转, 会让部分求值容易得多。 对流程图做部分求值得到剩余流程图。 运气好的话,其中的跳转可以变回 while 循环。 但一般做不到;我们在这里不追求这一点。

【基本块|Basic Block】

流程图由【基本块】构成,我们用归纳类型 block 表示它。 基本块是一串赋值(构造子 Assign), 以条件跳转(构造子 If)或无条件跳转(构造子 Goto)结束。 跳转的目的地由【标签】指定,标签可以是任意类型。 因此,我们用标签的类型来参数化 block 类型。
Inductive block (Label:Type) : Type :=
  | Goto : Label → block Label
  | If : bexp → Label → Label → block Label
  | Assign : string → aexp → block Label → block Label.

Arguments Goto {Label} _.
Arguments If {Label} _ _ _.
Arguments Assign {Label} _ _ _.
我们用上面在 Imp 中表达的「奇或偶」程序作为贯穿示例。 把这个程序转换成流程图需要 4 个标签,因此我们定义如下类型。
Inductive parity_label : Type :=
  | entry : parity_label
  | loop : parity_label
  | body : parity_label
  | done : parity_label.
下面的 block 是示例程序中 body 标签处的基本块。
Definition parity_body : block parity_label :=
  Assign Y <{Y - 1}>
   (Assign X <{1 - X}>
     (Goto loop)).
给定初始状态,对基本块求值就是计算最终状态与下一跳标签。 由于基本块不【包含】循环或其他控制结构, 对基本块的求值是全函数,我们无需担心不终止。
Fixpoint keval {L:Type} (st:state) (k : block L) : state × L :=
  match k with
  | Goto l ⇒ (st, l)
  | If b l1 l2 ⇒ (st, if beval st b then l1 else l2)
  | Assign i a k ⇒ keval (t_update st i (aeval st a)) k
  end.

Example keval_example:
  keval empty_st parity_body
  = ((X !-> 1 ; Y !-> 0), loop).
Proof. reflexivity. Qed.

【流程图程序|Flowchart Program】

流程图程序就是一个把标签映射到基本块的查找函数。 实际上,有些标签是【停机状态】,不映射到任何基本块。 因此更精确地,标签类型为 L 的流程图 program 是从 L 到 option (block L) 的函数。
Definition program (L:Type) : Type := L → option (block L).

Definition parity : program parity_label := fun l ⇒
  match l with
  | entry ⇒ Some (Assign X 0 (Goto loop))
  | loop ⇒ Some (If <{1 ≤ Y}> body done)
  | body ⇒ Some parity_body
  | done ⇒ None (* halt *)
  end.
与基本块不同,程序可能不终止, 因此我们用归纳关系 peval 而非递归函数 来对程序求值建模。
Inductive peval {L:Type} (p : program L)
  : state → L → state → L → Prop :=
  | E_None: ∀ st l,
    p l = None →
    peval p st l st l
  | E_Some: ∀ st l k st' l' st'' l'',
    p l = Some k →
    keval st k = (st', l') →
    peval p st' l' st'' l'' →
    peval p st l st'' l''.

Example parity_eval: peval parity empty_st entry empty_st done.
Proof. erewrite f_equal with (f := fun st ⇒ peval _ _ _ st _).
  eapply E_Some. reflexivity. reflexivity.
  eapply E_Some. reflexivity. reflexivity.
  apply E_None. reflexivity.
  apply functional_extensionality. intros i. rewrite t_update_same; auto.
Qed.

基本块与流程图程序的部分求值

部分求值以系统的方式改变标签类型: 若标签类型原为 L,则变为 pe_state × L。 于是原程序中的同一标签可能被展开(或膨胀)成 与不同部分状态配对的多个标签。 例如,parity 程序中的标签 loop 会变成两个标签: ([(X,0)], loop) 与 ([(X,1)], loop)。 这一标签类型的变化反映在随后定义的 pe_block 与 pe_program 的类型中。
Fixpoint pe_block {L:Type} (pe_st:pe_state) (k : block L)
  : block (pe_state × L) :=
  match k with
  | Goto l ⇒ Goto (pe_st, l)
  | If b l1 l2 ⇒
    match pe_bexp pe_st b with
    | BTrue ⇒ Goto (pe_st, l1)
    | BFalse ⇒ Goto (pe_st, l2)
    | b' ⇒ If b' (pe_st, l1) (pe_st, l2)
    end
  | Assign i a k ⇒
    match pe_aexp pe_st a with
    | ANum n ⇒ pe_block (pe_add pe_st i n) k
    | a' ⇒ Assign i a' (pe_block (pe_remove pe_st i) k)
    end
  end.

Example pe_block_example:
  pe_block [(X,0)] parity_body
  = Assign Y <{Y - 1}> (Goto ([(X,1)], loop)).
Proof. reflexivity. Qed.

Theorem pe_block_correct: ∀ (L:Type) st pe_st k st' pe_st' (l':L),
  keval st (pe_block pe_st k) = (st', (pe_st', l')) →
  keval (pe_update st pe_st) k = (pe_update st' pe_st', l').
Proof. intros. generalize dependent pe_st. generalize dependent st.
  induction k as [l | b l1 l2 | i a k];
    intros st pe_st H.
  - (* Goto *) inversion H; reflexivity.
  - (* If *)
    replace (keval st (pe_block pe_st (If b l1 l2)))
       with (keval st (If (pe_bexp pe_st b) (pe_st, l1) (pe_st, l2)))
       in H by (simpl; destruct (pe_bexp pe_st b); reflexivity).
    simpl in ×. rewrite pe_bexp_correct.
    destruct (beval st (pe_bexp pe_st b)); inversion H; reflexivity.
  - (* Assign *)
    simpl in ×. rewrite pe_aexp_correct.
    destruct (pe_aexp pe_st a); simpl;
      try solve [rewrite pe_update_update_add; apply IHk; apply H];
      solve [rewrite pe_update_update_remove; apply IHk; apply H].
Qed.

Definition pe_program {L:Type} (p : program L)
  : program (pe_state × L) :=
  fun pe_l ⇒ match pe_l with | (pe_st, l) ⇒
                option_map (pe_block pe_st) (p l)
              end.

Inductive pe_peval {L:Type} (p : program L)
  (st:state) (pe_st:pe_state) (l:L) (st'o:state) (l':L) : Prop :=
  | pe_peval_intro : ∀ st' pe_st',
    peval (pe_program p) st (pe_st, l) st' (pe_st', l') →
    pe_update st' pe_st' = st'o →
    pe_peval p st pe_st l st'o l'.

Theorem pe_program_correct:
  ∀ (L:Type) (p : program L) st pe_st l st'o l',
  peval p (pe_update st pe_st) l st'o l' ↔
  pe_peval p st pe_st l st'o l'.
Proof. intros.
  split.
  - (* -> *) intros Heval.
    remember (pe_update st pe_st) as sto.
    generalize dependent pe_st. generalize dependent st.
    induction Heval as
      [ sto l Hlookup | sto l k st'o l' st''o l'' Hlookup Hkeval Heval ];
      intros st pe_st Heqsto; subst sto.
    + (* E_None *) eapply pe_peval_intro. apply E_None.
      simpl. rewrite Hlookup. reflexivity. reflexivity.
    + (* E_Some *)
      remember (keval st (pe_block pe_st k)) as x.
      destruct x as [st' [pe_st' l'_] ].
      symmetry in Heqx. erewrite pe_block_correct in Hkeval by apply Heqx.
      inversion Hkeval. subst st'o l'_. clear Hkeval.
      edestruct IHHeval. reflexivity. subst st''o. clear IHHeval.
      eapply pe_peval_intro; [| reflexivity]. eapply E_Some; eauto.
      simpl. rewrite Hlookup. reflexivity.
  - (* <- *) intros [st' pe_st' Heval Heqst'o].
    remember (pe_st, l) as pe_st_l.
    remember (pe_st', l') as pe_st'_l'.
    generalize dependent pe_st. generalize dependent l.
    induction Heval as
      [ st [pe_st_ l_] Hlookup
      | st [pe_st_ l_] pe_k st' [pe_st'_ l'_] st'' [pe_st'' l'']
        Hlookup Hkeval Heval ];
      intros l pe_st Heqpe_st_l;
      inversion Heqpe_st_l; inversion Heqpe_st'_l'; repeat subst.
    + (* E_None *) apply E_None. simpl in Hlookup.
      destruct (p l'); [ solve [ inversion Hlookup ] | reflexivity ].
    + (* E_Some *)
      simpl in Hlookup. remember (p l) as k.
      destruct k as [k|]; inversion Hlookup; subst.
      eapply E_Some; eauto. apply pe_block_correct. apply Hkeval.
Qed.

(* 2026-11-26 15:55 *)