Records记录体:为 STLC 添加记录体

Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
From Stdlib Require Import Strings.String.
From PLF Require Import Maps.
From PLF Require Import Smallstep.
From PLF Require Import Stlc.

添加记录体

在 MoreStlc 一章中,我们看到【记录体|Record】如何可以仅仅 视为积类型嵌套使用的语法糖。对简单的示例来说这没问题。 但这种编码并非形式化的。实际上,如果我们真的以这种方式对待 记录体,这种转换会在解析器中进行,而这里我们将其略去。 这种编码也不太高效,对于被类型检查器拒绝的程序 也给不出好的错误消息。 因此,看看如何把记录体作为语言的一等公民来对待也很有趣。 本章展示了这一点。
请回忆我们之前给出的非形式化定义:
语法:
       t ::= 项:
           | {i=t, ..., i=t} 记录体
           | t.i 投影
           | ...

       v ::= 值:
           | {i=v, ..., i=v} 记录体值
           | ...

       T ::= 类型:
           | {i:T, ..., i:T} 记录类型
           | ...
归约:
tn ==> tn' (ST_Rcd)  

{i1=v1, ..., im=vm, in=tn, ...} ==> {i1=v1, ..., im=vm, in=tn', ...}
t1 ==> t1' (ST_Proj1)  

t1.i ==> t1'.i
   (ST_ProjRcd)  

{..., i=vi, ...}.i ==> vi
定型:
Gamma |-- t1 : T1     ...     Gamma |-- tn : Tn (T_Rcd)  

Gamma |-- {i1=t1, ..., in=tn} : {i1:T1, ..., in:Tn}
Gamma |-- t0 : {..., i:Ti, ...} (T_Proj)  

Gamma |-- t0.i : Ti

形式化记录体

语法与操作语义

要将记录类型的语法形式化,最显然的方式是这样的:
Module FirstTry.

Definition alist (X : Type) := list (string × X).

Inductive ty : Type :=
  | Base : string → ty
  | Arrow : ty → ty → ty
  | TRcd : (alist ty) → ty.
不幸的是,我们在这里遇到了 Rocq 的一个局限。 这个类型并未自动给出我们期望的【归纳法则|Induction Principle】。 TRcd 情形中的【归纳假设|Induction Hypothesis】没有给出列表中 ty 元素的任何信息,因此它对我们想做的证明毫无用处。
(* Check ty_ind.
   ====>
    ty_ind :
      forall P : ty -> Prop,
        (forall i : id, P (Base i)) ->
        (forall t : ty, P t -> forall t0 : ty, P t0
                            -> P (Arrow t t0)) ->
        (forall a : alist ty, P (TRcd a)) ->    (* ??? *)
        forall t : ty, P t
*)


End FirstTry.
有可能从 Rocq 得到更好的归纳法则,但这样做的细节并不十分漂亮。 我们得到的法则,也不如 Rocq 为简单的 Inductive 定义 自动生成的那些法则那样直观易用。
幸运的是,还有另一种形式化记录体的方式,在某种意义上 甚至更简单、更自然。我们不使用标准的 Rocq list 类型, 而是基本上把它的构造子(「nil」和「cons」) 纳入我们类型的语法之中。
类似地,在项这一层,我们有空记录体的构造子 trnil,以及把单个 字段加到字段列表前端的构造子 rcons。
Inductive tm : Type :=
  | tm_var : string → tm
  | tm_app : tm → tm → tm
  | tm_abs : string → ty → tm → tm
  (* 记录体 *)
  | tm_rproj : tm → string → tm
  | tm_rnil : tm
  | tm_rcons : string → tm → tm → tm.

Notation "x" := x (in custom stlc_ty at level 0, x global) : stlc_scope.

Notation "<{{ x }}>" := x (x custom stlc_ty).

Notation "( t )" := t (in custom stlc_ty at level 0, t custom stlc_ty) : stlc_scope.
Notation "S -> T" := (Ty_Arrow S T) (in custom stlc_ty at level 99, right associativity) : stlc_scope.

Notation "$( t )" := t (in custom stlc_ty at level 0, t constr) : stlc_scope.

Notation "$( x )" := x (in custom stlc_tm at level 0, x constr, only parsing) : stlc_scope.
Notation "x" := x (in custom stlc_tm at level 0, x constr at level 0) : stlc_scope.
Notation "<{ e }>" := e (e custom stlc_tm at level 200) : stlc_scope.
Notation "( x )" := x (in custom stlc_tm at level 0, x custom stlc_tm) : stlc_scope.

Notation "x y" := (tm_app x y) (in custom stlc_tm at level 10, left associativity) : stlc_scope.
Notation "\ x : t , y" :=
  (tm_abs x t y) (in custom stlc_tm at level 200, x global,
                     t custom stlc_ty,
                     y custom stlc_tm at level 200,
                     left associativity).
Coercion tm_var : string >-> tm.
Arguments tm_var _%_string.

Notation "'Base' x" := (Ty_Base x) (in custom stlc_ty at level 0, x constr at level 0) : stlc_scope.

Notation " l ':' t1 '::' t2" := (Ty_RCons l t1 t2) (in custom stlc_ty at level 0, l global, t1 custom stlc_ty at level 0, right associativity).
Notation " l := e1 '::' e2" := (tm_rcons l e1 e2) (in custom stlc_tm at level 3, right associativity).
Notation "'nil'" := (Ty_RNil) (in custom stlc_ty).
Notation "'nil'" := (tm_rnil) (in custom stlc_tm).
Notation "o --> l" := (tm_rproj o l) (in custom stlc_tm at level 0).
一些示例……
Open Scope string_scope.
Open Scope stlc_scope.

Notation a := "a".
Notation f := "f".
Notation g := "g".
Notation l := "l".
Notation A := <{{ Base "A" }}>.
Notation B := <{{ Base "B" }}>.
Notation k := "k".
Notation i1 := "i1".
Notation i2 := "i2".
{ i1:A }
(* Check (RCons i1 A RNil). *)
{ i1:A→B, i2:A }
(* Check (RCons i1 (Arrow A B)
           (RCons i2 A RNil)). *)

良构性

Check <{{ nil → nil }}>.
将记录体的抽象语法从列表推广到 nil/cons 表示所带来的一个问题是, 它引入了写出如下这种奇怪类型的可能性……
Definition weird_type := <{{ a : A :: B }}>.
其中记录类型的「尾部」实际上并不是一个记录类型!
我们将组织定型判断,使得诸如 weird_type 这样的非良构类型永远 不会被赋予项。为此,我们定义谓词 record_ty 和 record_tm, 它们识别记录类型与记录项,以及 well_formed_ty, 它排除非良构的类型。
首先,一个类型是记录类型,当它在最外层只由 RNil 和 RCons 构造。
Inductive record_ty : ty → Prop :=
  | RTnil :
        record_ty <{{ nil }}>
  | RTcons : ∀ i T1 T2,
        record_ty <{{ i : T1 :: T2 }}>.
据此,我们可以定义良构类型。
Inductive well_formed_ty : ty → Prop :=
  | wfBase : ∀ (i : string),
        well_formed_ty <{{ Base i }}>
  | wfArrow : ∀ T1 T2,
        well_formed_ty T1 →
        well_formed_ty T2 →
        well_formed_ty <{{ T1 → T2 }}>
  | wfRNil :
        well_formed_ty <{{ nil }}>
  | wfRCons : ∀ i T1 T2,
        well_formed_ty T1 →
        well_formed_ty T2 →
        record_ty T2 →
        well_formed_ty <{{ i : T1 :: T2 }}>.

Hint Constructors record_ty well_formed_ty : core.
注意 record_ty 不是递归的:它只检查最外层的构造子。另一方面, well_formed_ty 性质则验证整个类型是良构的,其意义是每个记录体 的尾部(RCons 的第二个参数)都是记录体。
当然,我们还应关注非良构的项,而不仅是类型;但类型检查无需额外的 well_formed_tm 定义就能排除它们,因为它已经检查了项的结构。 我们需要的只是 record_ty 的类似物:一个项由 trnil 和 rcons 构造时,它就是记录项。
Lemma wf_ty_example: well_formed_ty <{{ i1 : (A → A) :: i2 : (B → B) :: nil }}>.
Proof.
  auto.
Qed.

Inductive record_tm : tm → Prop :=
  | rtnil :
        record_tm <{ nil }>
  | rtcons : ∀ i t1 t2,
        record_tm <{ i := t1 :: t2 }>.

Hint Constructors record_tm : core.

替换

替换很容易扩展。

归约

一个记录体是值,当它的所有字段都是值。
Inductive value : tm → Prop :=
  | v_abs : ∀ x T2 t1,
      value <{ \ x : T2, t1 }>
  | v_rnil : value <{ nil }>
  | v_rcons : ∀ i v1 vr,
      value v1 →
      value vr →
      value <{ i := v1 :: vr }>.

Hint Constructors value : core.
为了定义归约,我们需要一个辅助函数从记录项中提取单个字段:
step 函数在投影规则中使用这项一级查找函数。

Inductive step : tm → tm → Prop :=
  | ST_AppAbs : ∀ x T2 t1 v2,
         value v2 →
         <{(\x:T2, t1) v2}> --> <{ [x:=v2]t1 }>
  | ST_App1 : ∀ t1 t1' t2,
         t1 --> t1' →
         <{t1 t2}> --> <{t1' t2}>
  | ST_App2 : ∀ v1 t2 t2',
         value v1 →
         t2 --> t2' →
         <{v1 t2}> --> <{v1 t2'}>
  | ST_Proj1 : ∀ t1 t1' i,
        t1 --> t1' →
        <{ t1 --> i }> --> <{ t1' --> i }>
  | ST_ProjRcd : ∀ tr i vi,
        value tr →
        tlookup i tr = Some vi →
        <{ tr --> i }> --> vi
  | ST_Rcd_Head : ∀ i t1 t1' tr2,
        t1 --> t1' →
        <{ i := t1 :: tr2 }> --> <{ i := t1' :: tr2 }>
  | ST_Rcd_Tail : ∀ i v1 tr2 tr2',
        value v1 →
        tr2 --> tr2' →
        <{ i := v1 :: tr2 }> --> <{ i := v1 :: tr2' }>

where "t '-->' t'" := (step t t').

Notation multistep := (multi step).
Notation "t1 '-->*' t2" := (multistep t1 t2) (at level 40).

Hint Constructors step : core.

定型

接下来我们定义定型规则。这些规则几乎是上面所展示推理规则的直接 转写。唯一显著的差别是使用了 well_formed_ty。 在非形式化的表述中,我们使用的语法只允许良构的记录类型, 因此不必添加单独的检查。
我们希望维持的一个健全条件是: 每当 has_type Gamma t T 成立时,well_formed_ty T 也成立。 这样 has_type 从不把非良构类型赋予项。 事实上,我们将在下面证明此定理。不过,我们不想让不必要的 well_formed_ty 使用弄乱 has_type 的定义。 相反,我们只把 well_formed_ty 检查放在需要的地方: 即对 has_type 的归纳调用并不会检查类型良构性的地方。 例如,我们在 T_Var 情形中检查 well_formed_ty T, 因为这里没有会强制这一点的归纳 has_type 调用。 类似地,在 T_Abs 情形中,我们要求 well_formed_ty T11 的证明,因为对 has_type 的归纳调用只保证 T12 是良构的。
Fixpoint Tlookup (i:string) (Tr:ty) : option ty :=
  match Tr with
  | <{{ i' : T :: Tr' }}> ⇒
      if String.eqb i i' then Some T else Tlookup i Tr'
  | _ ⇒ None
  end.

Definition context := partial_map ty.


Inductive has_type (Gamma : context) :tm → ty → Prop :=
  | T_Var : ∀ x T,
      Gamma x = Some T →
      well_formed_ty T →
      <{ Gamma |-- x \in T }>
  | T_Abs : ∀ x T11 T12 t12,
      well_formed_ty T11 →
      <{ x ⊢> T11; Gamma |-- t12 \in T12 }> →
      <{ Gamma |-- \x : T11, t12 \in T11 → T12 }>
  | T_App : ∀ T1 T2 t1 t2,
      <{ Gamma |-- t1 \in T1 → T2 }> →
      <{ Gamma |-- t2 \in T1 }> →
      <{ Gamma |-- ( t1 t2) \in T2 }>
  (* 记录体: *)
  | T_Proj : ∀ i t Ti Tr,
      <{ Gamma |-- t \in Tr }> →
      Tlookup i Tr = Some Ti →
      <{ Gamma |-- (t --> i) \in Ti }>
  | T_RNil :
      <{ Gamma |-- nil \in nil }>
  | T_RCons : ∀ i t T tr Tr,
      <{ Gamma |-- t \in T }> →
      <{ Gamma |-- tr \in Tr }> →
      record_ty Tr →
      record_tm tr →
      <{ Gamma |-- ( i := t :: tr) \in i : T :: Tr }>

where "<{ Gamma '|--' t '∈' T }>" := (has_type Gamma t T).

Hint Constructors has_type : core.

示例

练习: 2 stars,标准 (examples)

完成下面的证明。你可以随意使用 Rocq 的自动化功能。 不过,如果你对类型系统的工作方式还没有把握, 也许应该先用基本功能完成证明 (特别是用 apply 而非 eapply)。 然后再考虑用自动化压缩它。
在开始证明【任何东西】之前,先确保你理解它在说什么。 :-)
Lemma typing_example_2 :
  <{ empty |-- (\a : ( i1 : (A → A) :: i2 : (B → B) :: nil), a --> i2)
            ( i1 := (\a : A, a) :: i2 := (\a : B,a ) :: nil ) \in B → B }>.
Proof.
  (* 在这里填写 *) Admitted.

Example typing_nonexample :
  ¬ ∃ T,
     <{ (a ⊢> <{{ i2 : (A → A) :: nil }}>) |--
       ( i1 := (\a : B, a) :: a ) \in
               T }>.
Proof.
  (* 在这里填写 *) Admitted.

Example typing_nonexample_2 : ∀ y,
  ¬ ∃ T,
   <{ (y ⊢> A) |--
     (\a : ( i1 : A :: nil ), a --> i1 )
      ( i1 := y :: i2 := y :: nil ) \in T }>.
Proof.
  (* 在这里填写 *) Admitted.
☐

定型的性质

该系统的【可进性|Progress】与【保型性|Preservation】证明本质上 与纯简单类型 λ-演算相同,但我们需要添加一些涉及记录体的技术引理。

良构性

字段查找

引理:若 empty |-- v : T 且 Tlookup i T 返回 Some Ti, 则 tlookup i v 对某个满足 empty |-- ti ∈ Ti 的项 ti 返回 Some ti。
证明:对定型导出式 Htyp 归纳。 由于 Tlookup i T = Some Ti,T 必为记录类型。 这一点连同 v 是值的事实,通过观察即可排除大多数情形, 只留下 T_RCons。
若定型导出式的最后一步由 T_RCons 得出,则对某个 i0、t、 tr、T 和 Tr,有 t = rcons i0 t tr 且 T = RCons i0 T Tr。
这留下两种可能需要考虑:i0 = i 或否。
  • 若 i = i0,则由 Tlookup i (RCons i0 T Tr) = Some Ti 得 T = Ti。于是 t 本身即满足定理。
  • 另一方面,假设 i ≠ i0。那么
            Tlookup i T = Tlookup i Tr 且
            tlookup i t = tlookup i tr, 于是结论由归纳假设得出。 ☐
以下是形式化陈述:
Lemma lookup_field_in_value : ∀ v T i Ti,
  value v →
  <{ empty |-- v \in T }> →
  Tlookup i T = Some Ti →
  ∃ ti, tlookup i v = Some ti ∧ <{ empty |-- ti \in Ti }>.
Proof with eauto.
  intros v T i Ti Hval Htyp Hget.
  remember empty as Gamma.
  induction Htyp; subst; try solve_by_invert...
  - (* T_RCons *)
    simpl in Hget. simpl. destruct (String.eqb i i0).
    + (* i 为第一个字段 *)
      simpl. injection Hget as Hget. subst.
      ∃ t...
    + (* 取尾部 *)
      destruct IHHtyp2 as [vi [Hgeti Htypi] ]...
      inversion Hval... Qed.

可进性

Theorem progress : ∀ t T,
     <{ empty |-- t \in T }> →
     value t ∨ ∃ t', t --> t'.
Proof with eauto.
  (* 定理:假设 empty |-- t : T。那么以下二者之一成立:
       1. t 是值,或者
       2. 对某个 t',有 t --> t'。
     证明:对给定的定型导出式归纳。 *)

  intros t T Ht.
  remember empty as Gamma.
  generalize dependent HeqGamma.
  induction Ht; intros HeqGamma; subst.
  - (* T_Var *)
    (* 给定定型导出式的最后一条规则不可能是 T_Var,
       因为 empty |-- x : T 永远不成立(语境为空)。 *)

    inversion H.
  - (* T_Abs *)
    (* 若最后使用的是 T_Abs 规则,则 t = abs x T11 t12,
       它是一个值。 *)

    left...
  - (* T_App *)
    (* 若最后应用的规则是 T_App,则 t = t1 t2,而且由规则的
       形式可知:
         empty |-- t1 : T1 → T2
         empty |-- t2 : T1
       根据归纳假设,t1 和 t2 各自要么是值,要么能走一步。 *)

    right.
    destruct IHHt1; subst...
    + (* t1 为值 *)
      destruct IHHt2; subst...
      × (* t2 为值 *)
      (* 若 t1 和 t2 都是值,那么 t1 = abs x T11 t12,
         因为抽象是唯一可能具有箭头类型的值。而
         (abs x T11 t12) t2 --> [x:=t2]t12 由 ST_AppAbs 得出。 *)

        inversion H; subst; try solve_by_invert.
        ∃ <{ [x:=t2]t0 }>...
      × (* t2 走一步 *)
        (* 若 t1 是值且 t2 --> t2',则由 ST_App2 得
           t1 t2 --> t1 t2'。 *)

        destruct H0 as [t2' Hstp]. ∃ <{ t1 t2' }>...
    + (* t1 走一步 *)
      (* 最后,若 t1 --> t1',则由 ST_App1 得
         t1 t2 --> t1' t2。 *)

      destruct H as [t1' Hstp]. ∃ <{ t1' t2 }>...
  - (* T_Proj *)
    (* 若给定导出式的最后一条规则是 T_Proj,则 t = rproj t i
       且
           empty |-- t : (TRcd Tr)
       由归纳假设,t 要么是值,要么走一步。 *)

    right. destruct IHHt...
    + (* 记录体为值 *)
      (* 若 t 是值,我们可用引理 lookup_field_in_value 证明
         对某个 ti 有 tlookup i t = Some ti,再由
         ST_ProjRcd 得 rproj i t --> ti。 *)

      destruct (lookup_field_in_value _ _ _ _ H0 Ht H)
        as [ti [Hlkup _] ].
      ∃ ti...
    + (* 记录体走一步 *)
      (* 另一方面,若 t --> t',则由 ST_Proj1 得
         rproj t i --> rproj t' i。 *)

      destruct H0 as [t' Hstp]. ∃ <{ t' --> i }>...
  - (* T_RNil *)
    (* 若给定导出式的最后一条规则是 T_RNil,则 t = trnil,
       它是一个值。 *)

    left...
  - (* T_RCons *)
    (* 若最后一条规则是 T_RCons,则 t = rcons i t tr 且
         empty |-- t : T
         empty |-- tr : Tr
       由归纳假设,t 和 tr 各自要么是值,要么能走一步。 *)

    destruct IHHt1...
    + (* 头部为值 *)
      destruct IHHt2; try reflexivity.
      × (* 尾部为值 *)
      (* 若 t 和 tr 都是值,则 rcons i t tr 也是一个值。 *)
        left...
      × (* 尾部走一步 *)
        (* 若 t 是值且 tr --> tr',则由 ST_Rcd_Tail 得
           rcons i t tr --> rcons i t tr'。 *)

        right. destruct H2 as [tr' Hstp].
        ∃ <{ i := t :: tr'}>...
    + (* 头部走一步 *)
      (* 若 t --> t',则由 ST_Rcd_Head 得
         rcons i t tr --> rcons i t' tr。 *)

      right. destruct H1 as [t' Hstp].
      ∃ <{ i := t' :: tr }>... Qed.

弱化

弱化引理与纯 STLC 中的证明方式相同。
Lemma weakening : ∀ Gamma Gamma' t T,
     includedin Gamma Gamma' →
     <{ Gamma |-- t \in T }> →
     <{ Gamma' |-- t \in T }>.
Proof.
  intros Gamma Gamma' t T H Ht.
  generalize dependent Gamma'.
  induction Ht; eauto using includedin_update.
Qed.

Lemma weakening_empty : ∀ Gamma t T,
     <{ empty |-- t \in T }> →
     <{ Gamma |-- t \in T }>.
Proof.
  intros Gamma t T.
  eapply weakening.
  discriminate.
Qed.

保型性

如前所述,我们通过对项 t 归纳来证明【替换引理|Substitution Lemma】。 与 StlcProp.v 中的证明相比,唯一的新情形是 rcons。 对于此情形,我们必须多做一点工作,来表明对一个项做替换不改变 它是否为记录项。
Lemma substitution_preserves_typing : ∀ Gamma x U t v T,
  <{ x ⊢> U ; Gamma |-- t \in T }> →
  <{ empty |-- v \in U }> →
  <{ Gamma |-- [x:=v]t \in T }>.
Proof.
  intros Gamma x U t v T Ht Hv.
  generalize dependent Gamma. generalize dependent T.
  induction t; intros T Gamma H;
  (* 每种情形中,我们都要设法得到 H 的导出式 *)
    inversion H; clear H; subst; simpl; eauto.
  - (* var *)
    rename s into y. destruct (eqb_spec x y); subst.
    + (* x=y *)
      rewrite update_eq in H1.
      injection H1 as H1; subst.
      apply weakening_empty. assumption.
    + (* x<>y *)
      apply T_Var. rewrite update_neq in H1; auto. assumption.
  - (* abs *)
    rename s into y, t into T.
    destruct (eqb_spec x y); subst; apply T_Abs; try assumption.
    + (* x=y *)
      rewrite update_shadow in H5. assumption.
    + (* x<>y *)
      apply IHt.
      rewrite update_permute; auto.
  - (* rcons *) (* <=== 与纯 STLC 相比唯一的新情形 *)
     apply T_RCons; eauto.
     inversion H7; subst; simpl; auto.
Qed.

Theorem preservation : ∀ t t' T,
  <{ empty |-- t \in T }> →
  t --> t' →
  <{ empty |-- t' \in T }>.
Proof with eauto.
  intros t t' T HT. generalize dependent t'.
  remember empty as Gamma.
  induction HT;
       intros t' HE; subst;
       try solve [inversion HE; subst; auto].
  - (* T_App *)
    inversion HE; subst...
    + (* ST_AppAbs *)
      apply substitution_preserves_typing with T1...
      inversion HT1...
  - (* T_Proj *) (* <=== 与纯 STLC 相比的新情形 *)
    (* 若最后一条规则是 T_Proj,则 t = rproj t1 i。
       两条规则可能导致 t --> t':T_Proj1 和
       T_ProjRcd。前一种情形下 t' 的定型由归纳假设得出,
       因此我们只需考虑 T_ProjRcd。

       这里 t 是记录体值。由于使用了规则 T_Proj,我们知道
       对某个 i 和 Tr,有 empty |-- t ∈ Tr 且
       Tlookup i Tr = Some Ti。于是我们可以应用引理
       lookup_field_in_value 来找到该投影步进到的记录元素。 *)

    inversion HE; subst...
    destruct (lookup_field_in_value _ _ _ _ H2 HT H)
      as [vi [Hget Htyp] ].
    rewrite H4 in Hget. injection Hget as Hget. subst...
  - (* T_RCons *) (* <=== 与纯 STLC 相比的新情形 *)
    (* 若最后一条规则是 T_RCons,则对某个 i、t 和满足
       record_tm tr 的 tr,有 t = rcons i t tr。若该步进
       由 ST_Rcd_Head 得出,则结论由归纳假设直接得出。若该步进
       由 ST_Rcd_Tail 得出,则对某个 tr2' 有 tr --> tr2',
       我们还必须使用引理 step_preserves_record_tm 来表明
       record_tm tr2'。 *)

    inversion HE; subst...
    apply T_RCons... eapply step_preserves_record_tm...
Qed.

End STLCExtendedRecords.

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