From Hammer Require Import Hammer.

Require Import Arith.
Require Import Ascii.
Declare ML Module "string_syntax_plugin".

Inductive string : Set :=
| EmptyString : string
| String : ascii -> string -> string.

Delimit Scope string_scope with string.
Bind Scope string_scope with string.
Local Open Scope string_scope.

Definition string_dec : forall s1 s2 : string, {s1 = s2} + {s1 <> s2}.
Proof. hammer_hook "String" "String.string_dec".
decide equality; apply ascii_dec.
Defined.

Reserved Notation "x ++ y" (right associativity, at level 60).

Fixpoint append (s1 s2 : string) : string :=
match s1 with
| EmptyString => s2
| String c s1' => String c (s1' ++ s2)
end
where "s1 ++ s2" := (append s1 s2) : string_scope.

Fixpoint length (s : string) : nat :=
match s with
| EmptyString => 0
| String c s' => S (length s')
end.

Fixpoint get (n : nat) (s : string) {struct s} : option ascii :=
match s with
| EmptyString => None
| String c s' => match n with
| O => Some c
| S n' => get n' s'
end
end.

Theorem get_correct :
forall s1 s2 : string, (forall n : nat, get n s1 = get n s2) <-> s1 = s2.
Proof. hammer_hook "String" "String.get_correct".
intros s1; elim s1; simpl.
intros s2; case s2; simpl; split; auto.
intros H; generalize (H 0); intros H1; inversion H1.
intros; discriminate.
intros a s1' Rec s2; case s2; simpl; split; auto.
intros H; generalize (H 0); intros H1; inversion H1.
intros; discriminate.
intros H; generalize (H 0); simpl; intros H1; inversion H1.
case (Rec s).
intros H0; rewrite H0; auto.
intros n; exact (H (S n)).
intros H; injection H as H1 H2.
rewrite H2; trivial.
rewrite H1; auto.
Qed.

Theorem append_correct1 :
forall (s1 s2 : string) (n : nat),
n < length s1 -> get n s1 = get n (s1 ++ s2).
Proof. hammer_hook "String" "String.append_correct1".
intros s1; elim s1; simpl; auto.
intros s2 n H; inversion H.
intros a s1' Rec s2 n; case n; simpl; auto.
intros n0 H; apply Rec; auto.
apply lt_S_n; auto.
Qed.

Theorem append_correct2 :
forall (s1 s2 : string) (n : nat),
get n s2 = get (n + length s1) (s1 ++ s2).
Proof. hammer_hook "String" "String.append_correct2".
intros s1; elim s1; simpl; auto.
intros s2 n; rewrite plus_comm; simpl; auto.
intros a s1' Rec s2 n; case n; simpl; auto.
generalize (Rec s2 0); simpl; auto. intros.
rewrite <- Plus.plus_Snm_nSm; auto.
Qed.

Fixpoint substring (n m : nat) (s : string) : string :=
match n, m, s with
| 0, 0, _ => EmptyString
| 0, S m', EmptyString => s
| 0, S m', String c s' => String c (substring 0 m' s')
| S n', _, EmptyString => s
| S n', _, String c s' => substring n' m s'
end.

Theorem substring_correct1 :
forall (s : string) (n m p : nat),
p < m -> get p (substring n m s) = get (p + n) s.
Proof. hammer_hook "String" "String.substring_correct1".
intros s; elim s; simpl; auto.
intros n; case n; simpl; auto.
intros m; case m; simpl; auto.
intros a s' Rec; intros n; case n; simpl; auto.
intros m; case m; simpl; auto.
intros p H; inversion H.
intros m' p; case p; simpl; auto.
intros n0 H; apply Rec; simpl; auto.
apply Lt.lt_S_n; auto.
intros n' m p H; rewrite <- Plus.plus_Snm_nSm; simpl; auto.
Qed.

Theorem substring_correct2 :
forall (s : string) (n m p : nat), m <= p -> get p (substring n m s) = None.
Proof. hammer_hook "String" "String.substring_correct2".
intros s; elim s; simpl; auto.
intros n; case n; simpl; auto.
intros m; case m; simpl; auto.
intros a s' Rec; intros n; case n; simpl; auto.
intros m; case m; simpl; auto.
intros m' p; case p; simpl; auto.
intros H; inversion H.
intros n0 H; apply Rec; simpl; auto.
apply Le.le_S_n; auto.
Qed.

Fixpoint prefix (s1 s2 : string) {struct s2} : bool :=
match s1 with
| EmptyString => true
| String a s1' =>
match s2 with
| EmptyString => false
| String b s2' =>
match ascii_dec a b with
| left _ => prefix s1' s2'
| right _ => false
end
end
end.

Theorem prefix_correct :
forall s1 s2 : string,
prefix s1 s2 = true <-> substring 0 (length s1) s2 = s1.
Proof. hammer_hook "String" "String.prefix_correct".
intros s1; elim s1; simpl; auto.
intros s2; case s2; simpl; split; auto.
intros a s1' Rec s2; case s2; simpl; auto.
split; intros; discriminate.
intros b s2'; case (ascii_dec a b); simpl; auto.
intros e; case (Rec s2'); intros H1 H2; split; intros H3; auto.
rewrite e; rewrite H1; auto.
apply H2; injection H3; auto.
intros n; split; intros; try discriminate.
case n; injection H; auto.
Qed.

Fixpoint index (n : nat) (s1 s2 : string) : option nat :=
match s2, n with
| EmptyString, 0 =>
match s1 with
| EmptyString => Some 0
| String a s1' => None
end
| EmptyString, S n' => None
| String b s2', 0 =>
if prefix s1 s2 then Some 0
else
match index 0 s1 s2' with
| Some n => Some (S n)
| None => None
end
| String b s2', S n' =>
match index n' s1 s2' with
| Some n => Some (S n)
| None => None
end
end.

Opaque prefix.

Theorem index_correct1 :
forall (n m : nat) (s1 s2 : string),
index n s1 s2 = Some m -> substring m (length s1) s2 = s1.
Proof. hammer_hook "String" "String.index_correct1".
intros n m s1 s2; generalize n m s1; clear n m s1; elim s2; simpl;
auto.
intros n; case n; simpl; auto.
intros m s1; case s1; simpl; auto.
intros H; injection H as <-; auto.
intros; discriminate.
intros; discriminate.
intros b s2' Rec n m s1.
case n; simpl; auto.
generalize (prefix_correct s1 (String b s2'));
case (prefix s1 (String b s2')).
intros H0 H; injection H as <-; auto.
case H0; simpl; auto.
case m; simpl; auto.
case (index 0 s1 s2'); intros; discriminate.
intros m'; generalize (Rec 0 m' s1); case (index 0 s1 s2'); auto.
intros x H H0 H1; apply H; injection H1; auto.
intros; discriminate.
intros n'; case m; simpl; auto.
case (index n' s1 s2'); intros; discriminate.
intros m'; generalize (Rec n' m' s1); case (index n' s1 s2'); auto.
intros x H H1; apply H; injection H1; auto.
intros; discriminate.
Qed.

Theorem index_correct2 :
forall (n m : nat) (s1 s2 : string),
index n s1 s2 = Some m ->
forall p : nat, n <= p -> p < m -> substring p (length s1) s2 <> s1.
Proof. hammer_hook "String" "String.index_correct2".
intros n m s1 s2; generalize n m s1; clear n m s1; elim s2; simpl;
auto.
intros n; case n; simpl; auto.
intros m s1; case s1; simpl; auto.
intros H; injection H as <-.
intros p H0 H2; inversion H2.
intros; discriminate.
intros; discriminate.
intros b s2' Rec n m s1.
case n; simpl; auto.
generalize (prefix_correct s1 (String b s2'));
case (prefix s1 (String b s2')).
intros H0 H; injection H as <-; auto.
intros p H2 H3; inversion H3.
case m; simpl; auto.
case (index 0 s1 s2'); intros; discriminate.
intros m'; generalize (Rec 0 m' s1); case (index 0 s1 s2'); auto.
intros x H H0 H1 p; try case p; simpl; auto.
intros H2 H3; red; intros H4; case H0.
intros H5 H6; absurd (false = true); auto with bool.
intros n0 H2 H3; apply H; auto.
injection H1; auto.
apply Le.le_O_n.
apply Lt.lt_S_n; auto.
intros; discriminate.
intros n'; case m; simpl; auto.
case (index n' s1 s2'); intros; discriminate.
intros m'; generalize (Rec n' m' s1); case (index n' s1 s2'); auto.
intros x H H0 p; case p; simpl; auto.
intros H1; inversion H1; auto.
intros n0 H1 H2; apply H; auto.
injection H0; auto.
apply Le.le_S_n; auto.
apply Lt.lt_S_n; auto.
intros; discriminate.
Qed.

Theorem index_correct3 :
forall (n m : nat) (s1 s2 : string),
index n s1 s2 = None ->
s1 <> EmptyString -> n <= m -> substring m (length s1) s2 <> s1.
Proof. hammer_hook "String" "String.index_correct3".
intros n m s1 s2; generalize n m s1; clear n m s1; elim s2; simpl;
auto.
intros n; case n; simpl; auto.
intros m s1; case s1; simpl; auto.
case m; intros; red; intros; discriminate.
intros n' m; case m; auto.
intros s1; case s1; simpl; auto.
intros b s2' Rec n m s1.
case n; simpl; auto.
generalize (prefix_correct s1 (String b s2'));
case (prefix s1 (String b s2')).
intros; discriminate.
case m; simpl; auto with bool.
case s1; simpl; auto.
intros a s H H0 H1 H2; red; intros H3; case H.
intros H4 H5; absurd (false = true); auto with bool.
case s1; simpl; auto.
intros a s n0 H H0 H1 H2;
change (substring n0 (length (String a s)) s2' <> String a s);
apply (Rec 0); auto.
generalize H0; case (index 0 (String a s) s2'); simpl; auto; intros;
discriminate.
apply Le.le_O_n.
intros n'; case m; simpl; auto.
intros H H0 H1; inversion H1.
intros n0 H H0 H1; apply (Rec n'); auto.
generalize H; case (index n' s1 s2'); simpl; auto; intros;
discriminate.
apply Le.le_S_n; auto.
Qed.

Transparent prefix.

Theorem index_correct4 :
forall (n : nat) (s : string),
index n EmptyString s = None -> length s < n.
Proof. hammer_hook "String" "String.index_correct4".
intros n s; generalize n; clear n; elim s; simpl; auto.
intros n; case n; simpl; auto.
intros; discriminate.
intros; apply Lt.lt_O_Sn.
intros a s' H n; case n; simpl; auto.
intros; discriminate.
intros n'; generalize (H n'); case (index n' EmptyString s'); simpl;
auto.
intros; discriminate.
intros H0 H1; apply Lt.lt_n_S; auto.
Qed.

Definition findex n s1 s2 :=
match index n s1 s2 with
| Some n => n
| None => 0
end.


(* (c) Copyright Emilio Jesús Gallego Arias.                            *)
(* You may distribute this file under the terms of the CeCILL-B license *)
From mathcomp
Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.
From mathcomp
Require Import tuple.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(******************************************************************************)
(* ssreflect interfaces for Vector type                                       *)
(*                                                                            *)
(* We define a subType structure for vectors, over the same predicate than    *)
(* tuples, that is say, a vector of size n can be seen as a sequence s plus   *)
(* a proof of size s == n.                                                    *)
(*                                                                            *)
(* We can use valP and val_inj on vectors.                                    *)
(*                                                                            *)
(* We provide some lemmas for tuple to vector conversion (and viceversa),     *)
(* even if it does not make much sense to use them over pure tuples.          *)
(*                                                                            *)
(* Some examples are also provided at the end.                                *)
(*                                                                            *)
(* STATUS: experimental, everything will likely change                        *)
(*                                                                            *)
(******************************************************************************)

Fixpoint V (n : nat) T {struct n} : Type :=
  match n with
  | 0    => unit
  | n.+1 => (T * V n T)%type
  end.

Definition vnil  {T} : V 0 T := tt.
Definition vcons {T n} (x : T) (v : V n T) : V n.+1 T := (x,v).

Definition v_class n T := V n T.
Identity Coercion v_of_vclass : v_class >-> V.

Definition to_list {n T} (v : V n T) : seq T.
elim: n v => [_|n /= ihn [x]]; first exact: [::].
by move/ihn/(cons x); apply.
Defined.

Section SubVector.

  Section Conv.
  Variables (n : nat) (T : Type).

  Implicit Types (s : seq T).
  Implicit Types (v : V n T).

  (* XXX: Fix this coercion *)
  Coercion to_list : V >-> seq.

  Definition vP s := size s == n.

  Lemma vtSP v : vP v.
  Proof. rewrite /vP; elim: n v => //= n' ihn [x v] /=.
         exact: (ihn v).
  Defined.

  Definition tvS s (p : vP s) : V n T.
  Proof.
    rewrite /vP in p.
    (* We match on the index n, this is a good compromise to
       have reduction... *)
    elim: s n p => [|x s ih] [|n0] // p.
    exact: vcons _ (ih _ _).
  Defined.
  End Conv.

  Lemma tvSK T n (v : V n T) : tvS (vtSP v) = v.
  Proof. by elim: n v => [[//]|n ihn [x v]]; rewrite /= ihn. Qed.

  Lemma vtSPK T n (s : seq T) (Px : vP n s) : s = tvS Px.
  Proof. by elim: n s Px => [ | n ih ] [] //= x s Px; rewrite {1}[s]ih. Qed.

  Lemma vecSub n T : subType (@vP n T).
  Proof.
    apply: (SubType (V n T) (@to_list n T) (@tvS n T)).
    - by move=> K P u; rewrite -[u]tvSK.
    - by move=> x Px; rewrite -vtSPK.
  Defined.

  Canonical V_subType := Eval hnf in vecSub.

  (* EG: Ummm: is this OK? *)
  Canonical V_tuple T n v := Eval hnf in Tuple (@vtSP n T v).

  (* Lemma k (T : eqType) : [tuple] == [tuple of (@vnil T)]. *)
  (* Lemma k' (T : eqType) : [tuple] == V_tuple (@vnil T). *)

End SubVector.

Section EqVector.

  Variables (n : nat) (T : eqType).

  Definition vector_eqMixin := Eval hnf in [eqMixin of V n T by <:].
  Canonical  vector_eqType  := Eval hnf in EqType _ vector_eqMixin.

  Canonical vector_predType :=
    Eval hnf in mkPredType (fun t : V n T => mem_seq (to_list t)).

  (* Lemma f n (T : eqType) (x : T) (v : V n T) : x \in v. *)

End EqVector.

Definition vector_choiceMixin n (T : choiceType) :=
  [choiceMixin of V n T by <:].

Canonical vector_choiceType n (T : choiceType) :=
  Eval hnf in ChoiceType (V n T) (vector_choiceMixin n T).

Definition vector_countMixin n (T : countType) :=
  [countMixin of V n T by <:].

Canonical vector_countType n (T : countType) :=
  Eval hnf in CountType (V n T) (vector_countMixin n T).

Canonical vector_subCountType n (T : countType) :=
  Eval hnf in [subCountType of V n T].

(* Canonical vector_finMixin := Eval hnf in FinMixin (@FinTuple.enumP n T). *)
(* Canonical vector_finType  := Eval hnf in FinType (V n T) vector_finMixin. *)
(* Canonical vector_subFinType := Eval hnf in [subFinType of V n T]. *)

(* Canonical image_vector : #|A|.-tuple T' := [tuple of image f A]. *)
(* Canonical codom_tuple : #|T|.-tuple T' := [tuple of codom f]. *)

(* Canonical vector_subCountType n (T : countType) := *)
(*   Eval hnf in [subCountType of V n T]. *)

Section VecTuple.

  Variable (T : Type).

  Definition tv_def n (u : n.-tuple T) : V n T.
  Proof. by case: u => _ /tvS. Defined.

  Definition tv := nosimpl tv_def.

  Lemma tv_nil : tv [tuple] = (@vnil T).
  Proof. by []. Qed.

  Lemma tv_cons n x (xs : n.-tuple T) :
    tv [tuple of x :: xs] = vcons x (tv xs).
  Proof.
    case: xs => xs hxs.
    congr (vcons _ (tvS _)).
    exact: bool_irrelevance.
  Qed.

  (* This definition is nicer when compared to vt' *)
  Definition vt_def n (v : V n T) : n.-tuple T.
  Proof.
    elim: n v => [ ? | n ihn /= [x vt]].
    - exact: [tuple].
    - exact: [tuple of x :: (ihn vt)].
  Defined.

  Definition vt := nosimpl vt_def.

  Prenex Implicits vt tv.

  Lemma vt_cons n x (xs : V n T) :
    vt (vcons x xs) = [tuple of x :: vt xs].
  Proof. by []. Qed.

  Lemma tvK n : cancel (@vt n) tv.
  Proof.
    elim: n => [ [] | n ih [x v] ].
    - by [].
    - by rewrite tv_cons ih.
  Qed.

  Lemma vtK n : cancel (@tv n) vt.
  Proof.
    elim: n => [t | n ih t].
    - by rewrite [t]tuple0.
    - by rewrite [t]tuple_eta tv_cons vt_cons (ih (behead_tuple t)).
  Qed.

  Lemma tvI n : injective (@tv n).
  Proof. exact: can_inj (@vtK n). Qed.

  Lemma vtI n : injective (@vt n).
  Proof. exact: can_inj (@tvK n). Qed.

  (* This definition is slightly worse...? *)
  Definition vt' n (v : V n T) : n.-tuple T := Tuple (vtSP v).

  Lemma vt'_cons n x (xs : V n T) :
    vt' (vcons x xs) = [tuple of x :: vt' xs].
  Proof. exact: val_inj. Qed.

End VecTuple.

Module FinVector.
Section FinVector.
Variables (n : nat) (T : finType).

(* Generate all the vectors of size n from T *)
Definition enum_def : seq (V n T) :=
  seq.map (@tv T n) (FinTuple.enum n T).

Definition enum := nosimpl enum_def.

Lemma eq_tv_vt (v : V n T) : [pred x | tv x == v] =1 [pred x | x == vt v].
Proof. by move=> t; rewrite /= -{1}[v]tvK inj_eq //; exact: tvI. Qed.

Lemma enumP : Finite.axiom enum.
Proof.
  move=> t.
  by rewrite count_map (eq_count (eq_tv_vt _)) -(FinTuple.enumP (vt t)).
Qed.

End FinVector.
End FinVector.

Section UseFinVector.

Variables (n : nat) (T : finType).

Canonical vector_finMixin := Eval hnf in FinMixin (@FinVector.enumP n T).
Canonical vector_finType  := Eval hnf in FinType (V n T) vector_finMixin.
Canonical vector_subFinType := Eval hnf in [subFinType of V n T].

End UseFinVector.

Section IndVec.

  (* TODO: Define a principle to prove things over t A n, but in such
     a way that the subcases are handled over standard lists plus a
     size predicate about them *)

  Definition kk (A : Type) m t (x : A) (H : size t == m) : size (x :: t) == m.+1.
  Proof. by []. Qed.

  Definition vec_rect :
    forall (A : Type) (P : forall n : nat, V n A -> Type),
      (P 0 (vnil)) ->
      (forall (h : A) (n : nat) (t : seq A) (H : size t == n),
         P n (tvS H) -> P n.+1 (tvS (kk h H))) ->
    forall (n : nat) (t : V n A), P n t.
  Proof.
  move=> T P Hnil Hcons n.
  elim: n => [|n ihn] [//=] x t.
  rewrite -[t]tvSK.
  move: (Hcons x n t (vtSP t)).
  by rewrite (eq_irrelevance (kk x _) (vtSP _)); apply.
  Qed.

(*
  Definition vec_rect :
    forall (A : Type) (P : forall n : nat, t A n -> Type),
      (P 0 (nil A) ->
      (forall (h : A) (n : nat) (t : t A n), P n t -> P n.+1 (cons A h n t)) ->
    forall (n : nat) (t : t A n), P n t

*)


(* ZF *)

Require Import Utf8.
Require List.
Import List.ListNotations.
Open Scope list_scope.

Reserved Notation "x '∈' S" (at level 60).
Reserved Notation "x '∉' S" (at level 60).
Reserved Notation "A '⊂' B" (at level 60).
Reserved Notation "A '⋃' B" (at level 50).
Reserved Notation "A '∩' B" (at level 40).
Reserved Notation "'∅'" (at level 0).
Reserved Notation "'〈' x '〉'" (at level 0).
Reserved Notation "'〈' x , y '〉'" (at level 0).

Class ZF := mkZF
  { zf_set : Type;
    zf_mem : zf_set → zf_set → Prop
      where "x '∈' S" := (zf_mem x S)
      and "x '∉' S" := (¬ zf_mem x S);
    zf_incl A B := ∀ x, x ∈ A → x ∈ B where "A '⊂' B" := (zf_incl A B);
    zf_extens : ∀ A B, A ⊂ B → B ⊂ A → A = B;
    zf_pair : zf_set → zf_set → zf_set where "'〈' x , y '〉'" := (zf_pair x y);
    zf_single : zf_set → zf_set where "'〈' x '〉'" := (zf_single x);
    zf_empty : zf_set where "'∅'" := (zf_empty);

    zf_union : zf_set → zf_set → zf_set where "A '⋃' B" := (zf_union A B);
    zf_inter : zf_set → zf_set → zf_set where "A '∩' B" := (zf_inter A  B);
    zf_part : ∀ a, ∃ c, ∀ x, x ∈ c → x ⊂ a;
    zf_inf : ∃ Y, ∅ ∈ Y ∧∀ y, y ∈ Y → y ⋃ 〈 y 〉 ∈ Y;
    zf_found : ∀ x, x ≠ ∅ → ∃ y, y ∈ x ∧ y ∩ x = ∅;
    zf_sch_repl : ∀ F, (∀ x y z, F x y ∧ F x z → y = z) → zf_set → zf_set;

    zf_pair_prop : ∀ a b x, x ∈ 〈 a, b 〉 ↔ x = a ∨ x = b;
    zf_single_prop : ∀ x y, y ∈ 〈 x 〉 ↔ y = x;
    zf_empty_prop : ∀ x, x ∉ ∅;
    zf_union_prop : ∀ A B x, x ∈ A ⋃ B ↔ x ∈ A ∨ x ∈ B;
    zf_inter_prop : ∀ A B x, x ∈ A ∩ B ↔ x ∈ A ∧ x ∈ B;
    zf_sch_repl_prop : ∀ F P A B,
      B = zf_sch_repl F P A ↔ (∀ y, y ∈ B ↔ ∃ x, x ∈ A ∧ F x y) }.

Notation "'∅'" := (zf_empty).
Notation "'〈' x '〉'" := (zf_single x).
Notation "'〈' x , y '〉'" := (zf_pair x y).
Notation "x '∈' S" := (zf_mem x S).
Notation "x '∉' S" := (¬ zf_mem x S).
Notation "A '⊂' B" := (zf_incl A B).
Notation "A '⋃' B" := (zf_union A B).
Notation "A '∩' B" := (zf_inter A B).

Theorem empty_is_subset {zf : ZF} : ∀ A, ∅ ⊂ A.
Proof.
intros A x Hx.
now apply zf_empty_prop in Hx.
Qed.

Theorem empty_union_any {zf : ZF} : ∀ A, ∅ ⋃ A = A.
Proof.
intros.
apply zf_extens; intros x H.
-apply zf_union_prop in H.
 destruct H as [H| ]; [ | easy ].
 now apply zf_empty_prop in H.
-now apply zf_union_prop; right.
Qed.

Theorem empty_inter_any {zf : ZF} : ∀ A, ∅ ∩ A = ∅.
Proof.
intros.
apply zf_extens; intros x H.
-now apply zf_inter_prop in H.
-now apply zf_empty_prop in H.
Qed.

Theorem subset_of_empty {zf : ZF} : ∀ A, A ⊂ ∅ → A = ∅.
Proof.
intros * HA.
apply zf_extens; intros x H.
-now apply HA.
-now apply zf_empty_prop in H.
Qed.

Theorem not_elem_itself {zf : ZF} : ∀ A, A ∉ A.
Proof.
intros A H1.
assert (H2 : zf_single A ≠ ∅). {
  intros H2.
  assert (H3 : A ∈ zf_single A) by now apply zf_single_prop.
  rewrite H2 in H3.
  now apply zf_empty_prop in H3.
}
specialize (zf_found (zf_single A) H2) as (B & H3 & H4).
apply zf_single_prop in H3.
rewrite H3 in H4.
clear H3.
rewrite <- H4 in H2.
apply H2.
apply zf_extens; intros x H.
-apply zf_inter_prop.
 split; [ | easy ].
 apply zf_single_prop in H.
 now subst x.
-now apply zf_inter_prop in H.
Qed.

Theorem pair_same {zf : ZF} : ∀ x, zf_pair x x = zf_single x.
Proof.
intros.
apply zf_extens; intros y H.
-apply zf_single_prop.
 apply zf_pair_prop in H.
 now destruct H.
-apply zf_pair_prop.
 apply zf_single_prop in H.
 now left.
Qed.

Theorem union_comm {zf : ZF} : ∀ A B, A ⋃ B = B ⋃ A.
Proof.
intros.
apply zf_extens; intros x H.
-apply zf_union_prop in H.
 apply zf_union_prop.
 now apply or_comm.
-apply zf_union_prop in H.
 apply zf_union_prop.
 now apply or_comm.
Qed.

Theorem union_half_assoc {zf : ZF} : ∀ A B C x,
  x ∈ (C ⋃ B) ⋃ A → x ∈ (A ⋃ B) ⋃ C.
Proof.
intros * H.
apply zf_union_prop in H.
apply zf_union_prop.
destruct H as [H| H].
-apply zf_union_prop in H.
 destruct H as [H| H]; [ now right | ].
 now left; apply zf_union_prop; right.
-now left; apply zf_union_prop; left.
Qed.

Theorem union_assoc {zf : ZF} : ∀ A B C, A ⋃ (B ⋃ C) = (A ⋃ B) ⋃ C.
Proof.
intros.
rewrite union_comm.
replace (B ⋃ C) with (C ⋃ B) by apply union_comm.
now apply zf_extens; intros x H; apply union_half_assoc.
Qed.

Theorem inter_comm {zf : ZF} : ∀ A B, A ∩ B = B ∩ A.
Proof.
intros.
apply zf_extens; intros x H.
-apply zf_inter_prop in H.
 apply zf_inter_prop.
 now apply and_comm.
-apply zf_inter_prop in H.
 apply zf_inter_prop.
 now apply and_comm.
Qed.

Theorem inter_half_assoc {zf : ZF} : ∀ A B C x,
  x ∈ (C ∩ B) ∩ A → x ∈ (A ∩ B) ∩ C.
Proof.
intros * H.
apply zf_inter_prop in H.
apply zf_inter_prop.
destruct H as (H1, H2).
apply zf_inter_prop in H1.
destruct H1 as (H1, H3).
split; [ | easy ].
now apply zf_inter_prop.
Qed.

Theorem inter_assoc {zf : ZF} : ∀ A B C, A ∩ (B ∩ C) = (A ∩ B) ∩ C.
Proof.
intros.
rewrite inter_comm.
replace (B ∩ C) with (C ∩ B) by apply inter_comm.
now apply zf_extens; intros x H; apply inter_half_assoc.
Qed.

Theorem inter_union_distr {zf : ZF} : ∀ A B C,
  A ∩ (B ⋃ C) = (A ∩ B) ⋃ (A ∩ C).
Proof.
intros.
apply zf_extens; intros x H.
-apply zf_inter_prop in H.
 destruct H as (H1, H2).
 apply zf_union_prop in H2.
 apply zf_union_prop.
 destruct H2 as [H2| H2].
 +now left; apply zf_inter_prop.
 +now right; apply zf_inter_prop.
-apply zf_union_prop in H.
 apply zf_inter_prop.
 destruct H as [H| H]; apply zf_inter_prop in H.
 +split; [ easy | ].
  now apply zf_union_prop; left.
 +split; [ easy | ].
  now apply zf_union_prop; right.
Qed.

Theorem union_inter_distr {zf : ZF} : ∀ A B C,
  A ⋃ (B ∩ C) = (A ⋃ B) ∩ (A ⋃ C).
Proof.
intros.
apply zf_extens; intros x H.
-apply zf_union_prop in H.
 apply zf_inter_prop.
 destruct H as [H| H].
 +now split; apply zf_union_prop; left.
 +apply zf_inter_prop in H.
  now split; apply zf_union_prop; right.
-apply zf_inter_prop in H.
 destruct H as (H1, H2).
 apply zf_union_prop in H1.
 apply zf_union_prop in H2.
 apply zf_union_prop.
 destruct H1 as [H1| H1]; [ now left | ].
 destruct H2 as [H2| H2]; [ now left | ].
 now right; apply zf_inter_prop.
Qed.

(* *)

Definition zf_ord_pair {zf : ZF} a b := zf_pair (zf_single a) (zf_pair a b).

(* mouais, chais pas si c'est ça *)
Definition zf_function {zf : ZF} A B F P :=
(*
  let '(F, P) := FP in
*)
  zf_ord_pair (zf_ord_pair A B) (zf_sch_repl F P A).

Check zf_function.

(*
Record category {zf : ZF} := mkcat
  { ca_obj : zf_set;
    ca_arr : zf_set;
    ca_comp : zf_set → zf_set → zf_set;
    ca_arr_prop : ∀ a, a ∈ ca_arr →
      ∃ o₁ o₂, o₁ ∈ ca_obj ∧ o₂ = ca_obj ∧ a = zf_ord_pair o₁ o₂;
    ca_comp_prop : ∀ a₁ a₂, a₁ ∈ ca_arr → a₂ ∈ ca_arr →
      ∃ o₁ o₂ o₃, o₁ ∈ ca_obj ∧ o₂ ∈ ca_obj ∧ o₃ ∈ ca_obj ∧
      a₁ = zf_ord_pair o₁ o₂ ∧ a₂ = zf_ord_pair o₂ o₃ ∧
      ca_comp a₁ a₂ = zf_ord_pair o₁ o₃ }.

Definition cat_Set :=
  {| ca_obj := ... ???

Definition cat_Mat := ...
...
*)


(** * NormInType: Alternate Version of Normalization, for Extraction *)

(* $Date: 2012-04-16 20:14:27 -0400 (Mon, 16 Apr 2012) $ *)
(* Chapter maintained by Andrew Tolmach and Benjamin Pierce *)

(** * Note *)

(** This is an alternate version of [Norm.v] that is used as an
    example in [Extraction2.v].  It is not intended to be read on its
    own. *)

(** * Normalization *)

Require Import Stlc.

(**
(This chapter is optional.)

In this chapter, we consider another fundamental theoretical property
of the simply typed lambda-calculus: the fact that the evaluation of a
well-typed program is guaranteed to halt in a finite number of
steps---i.e., every well-typed term is _normalizable_.

Unlike the type-safety properties we have considered so far, the
normalization property does not extend to full-blown programming
languages, because these languages nearly always extend the simply
typed lambda-calculus with constructs, such as general recursion
(as we discussed in the MoreStlc chapter) or recursive types, that can
be used to write nonterminating programs.  However, the issue of
normalization reappears at the level of _types_ when we consider the
metatheory of polymorphic versions of the lambda calculus such as
F_omega: in this system, the language of types effectively contains a
copy of the simply typed lambda-calculus, and the termination of the
typechecking algorithm will hinge on the fact that a ``normalization''
operation on type expressions is guaranteed to terminate.

Another reason for studying normalization proofs is that they are some
of the most beautiful---and mind-blowing---mathematics to be found in
the type theory literature, often (as here) involving the fundamental
proof technique of _logical relations_.

The calculus we shall consider here is the simply typed
lambda-calculus over a single base type [bool] and with pairs. We'll
give full details of the development for the basic lambda-calculus
terms treating [bool] as an uninterpreted base type, and leave the
extension to the boolean operators and pairs to the reader.  Even for
the base calculus, normalization is not entirely trivial to prove,
since each reduction of a term can duplicate redexes in subterms. *)

(** **** Exercise: 1 star *)
(** Where do we fail if we attempt to prove normalization by a
straightforward induction on the size of a well-typed term? *)

(* FILL IN HERE *)
(** [] *)

(* ###################################################################### *)
(** * Language *)

(** We begin by repeating the relevant language definition, which is
similar to those in the MoreStlc chapter, and supporting results
including type preservation and step determinism.  (We won't need
progress.)  You may just wish to skip down to the Normalization
section... *)

(* ###################################################################### *)
(** *** Syntax and Operational Semantics *)

Inductive ty : Type :=
  | TBool : ty
  | TArrow : ty -> ty -> ty

.

Tactic Notation "T_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "TBool" | Case_aux c "TArrow" | Case_aux c "TProd" ].

Inductive tm : Type :=
    (* pure STLC *)
  | tvar : id -> tm
  | tapp : tm -> tm -> tm
  | tabs : id -> ty -> tm -> tm

    (* booleans *)
  | ttrue : tm
  | tfalse : tm
  | tif : tm -> tm -> tm -> tm.
          (* i.e., [if t0 then t1 else t2] *)

Tactic Notation "t_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"

  | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ].

(* ###################################################################### *)
(** *** Substitution *)

Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
  match t with
  | tvar y => if beq_id x y then s else t
  | tabs y T t1 =>  tabs y T (if beq_id x y then t1 else (subst x s t1))
  | tapp t1 t2 => tapp (subst x s t1) (subst x s t2)

  | ttrue => ttrue
  | tfalse => tfalse
  | tif t0 t1 t2 => tif (subst x s t0) (subst x s t1) (subst x s t2)
  end.

Notation "'[' x ':=' s ']' t" := (subst x s t) (at level 20).

(* ###################################################################### *)
(** *** Reduction *)

Inductive value : tm -> Type :=
  | v_abs : forall x T11 t12,
      value (tabs x T11 t12)

  | v_true : value ttrue
  | v_false : value tfalse
.

Hint Constructors value.

Reserved Notation "t1 '==>' t2" (at level 40).

Inductive step : tm -> tm -> Type :=
  | ST_AppAbs : forall x T11 t12 v2,
         value v2 ->
         (tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
  | ST_App1 : forall t1 t1' t2,
         t1 ==> t1' ->
         (tapp t1 t2) ==> (tapp t1' t2)
  | ST_App2 : forall v1 t2 t2',
         value v1 ->
         t2 ==> t2' ->
         (tapp v1 t2) ==> (tapp v1 t2')

  (* booleans *)
  | ST_IfTrue : forall t1 t2,
        (tif ttrue t1 t2) ==> t1
  | ST_IfFalse : forall t1 t2,
        (tif tfalse t1 t2) ==> t2
  | ST_If : forall t0 t0' t1 t2,
        t0 ==> t0' ->
        (tif t0 t1 t2) ==> (tif t0' t1 t2)

where "t1 '==>' t2" := (step t1 t2).

Tactic Notation "step_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"

  | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].

Definition relation (X:Type) := X -> X -> Type.

Inductive multi (X:Type) (R: relation X)
                            : X -> X -> Type :=
  | multi_refl  : forall (x : X),
                 multi X R x x
  | multi_step : forall (x y z : X),
                    R x y ->
                    multi X R y z ->
                    multi X R x z.
Implicit Arguments multi [[X]].

Tactic Notation "multi_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "multi_refl" | Case_aux c "multi_step" ].

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

Hint Constructors step.

Inductive ex (X:Type) (P : X->Type) : Type :=
  ex_intro : forall (witness:X), P witness -> ex X P.

Notation "'exists' x , p" := (ex _ (fun x => p))
  (at level 200, x ident, right associativity) : type_scope.
Notation "'exists' x : X , p" := (ex _ (fun x:X => p))
  (at level 200, x ident, right associativity) : type_scope.

Definition normal_form {X:Type} (R:relation X) (t:X) : Type :=
  (exists t', R t t') -> False.

Notation step_normal_form := (normal_form step).

Definition deterministic {X: Type} (R: relation X) :=
  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.

Hint Constructors ex.

Lemma value__normal : forall t, value t -> step_normal_form t.
Proof with eauto.
  intros t H; induction H; intros [t' ST]; inversion ST...
Qed.

(* ###################################################################### *)
(** *** Typing *)

Definition context := partial_map ty.

Inductive has_type : context -> tm -> ty -> Type :=
  (* Typing rules for proper terms *)
  | T_Var : forall Gamma x T,
      Gamma x = Some T ->
      has_type Gamma (tvar x) T
  | T_Abs : forall Gamma x T11 T12 t12,
      has_type (extend Gamma x T11) t12 T12 ->
      has_type Gamma (tabs x T11 t12) (TArrow T11 T12)
  | T_App : forall T1 T2 Gamma t1 t2,
      has_type Gamma t1 (TArrow T1 T2) ->
      has_type Gamma t2 T1 ->
      has_type Gamma (tapp t1 t2) T2

  (* booleans *)
  | T_True : forall Gamma,
      has_type Gamma ttrue TBool
  | T_False : forall Gamma,
      has_type Gamma tfalse TBool
  | T_If : forall Gamma t0 t1 t2 T,
      has_type Gamma t0 TBool ->
      has_type Gamma t1 T ->
      has_type Gamma t2 T ->
      has_type Gamma (tif t0 t1 t2) T
.

Hint Constructors has_type.

Tactic Notation "has_type_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"

  | Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If" ].

Hint Extern 2 (has_type _ (tapp _ _) _) => eapply T_App; auto.
Hint Extern 2 (_ = _) => compute; reflexivity.

(* ###################################################################### *)
(** *** Context Invariance *)

Inductive appears_free_in : id -> tm -> Type :=
  | afi_var : forall x,
      appears_free_in x (tvar x)
  | afi_app1 : forall x t1 t2,
      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
  | afi_app2 : forall x t1 t2,
      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
  | afi_abs : forall x y T11 t12,
        y <> x  ->
        appears_free_in x t12 ->
        appears_free_in x (tabs y T11 t12)

  (* booleans *)
  | afi_if0 : forall x t0 t1 t2,
      appears_free_in x t0 ->
      appears_free_in x (tif t0 t1 t2)
  | afi_if1 : forall x t0 t1 t2,
      appears_free_in x t1 ->
      appears_free_in x (tif t0 t1 t2)
  | afi_if2 : forall x t0 t1 t2,
      appears_free_in x t2 ->
      appears_free_in x (tif t0 t1 t2)
.

Hint Constructors appears_free_in.

Definition closed (t:tm) :=
  forall x, appears_free_in x t -> False.

Lemma context_invariance : forall Gamma Gamma' t S,
     has_type Gamma t S  ->
     (forall x, appears_free_in x t -> Gamma x = Gamma' x)  ->
     has_type Gamma' t S.
Proof with eauto.
  intros Gamma Gamma' t S H H0. generalize dependent Gamma'.
  has_type_cases (induction H) Case;
    intros Gamma' Heqv...
  Case "T_Var".
    apply T_Var... rewrite <- Heqv...
  Case "T_Abs".
    apply T_Abs... apply IHhas_type. intros y Hafi.
    unfold extend. remember (beq_id x y) as e.
    destruct e...

  Case "T_If".
    eapply T_If...
Qed.

Lemma free_in_context : forall x t T Gamma,
   appears_free_in x t ->
   has_type Gamma t T ->
   exists T', Gamma x = Some T'.
Proof with eauto.
  intros x t T Gamma Hafi Htyp.
  has_type_cases (induction Htyp) Case; inversion Hafi; subst...
  Case "T_Abs".
    destruct IHHtyp as [T' Hctx]... exists T'.
    unfold extend in Hctx.
    apply not_eq_beq_id_false in H2. rewrite H2 in Hctx...
Qed.

Corollary typable_empty__closed : forall t T,
    has_type empty t T  ->
    closed t.
Proof.
  intros t T H. unfold closed. intros x H1.
  destruct (free_in_context _ _ _ _ H1 H) as [T' C].
  inversion C.  Qed.

(* ###################################################################### *)
(** *** Preservation *)

Lemma substitution_preserves_typing : forall Gamma x U v t S,
     has_type (extend Gamma x U) t S  ->
     has_type empty v U   ->
     has_type Gamma ([x:=v]t) S.
Proof with eauto.
  (* Theorem: If Gamma,x:U |- t : S and empty |- v : U, then
     Gamma |- ([x:=v]t) S. *)
  intros Gamma x U v t S Htypt Htypv.
  generalize dependent Gamma. generalize dependent S.
  (* Proof: By induction on the term t.  Most cases follow directly
     from the IH, with the exception of tvar and tabs.
     The former aren't automatic because we must reason about how the
     variables interact. *)
  t_cases (induction t) Case;
    intros S Gamma Htypt; simpl; inversion Htypt; subst...
  Case "tvar".
    simpl. rename i into y.
    (* If t = y, we know that
         [empty |- v : U] and
         [Gamma,x:U |- y : S]
       and, by inversion, [extend Gamma x U y = Some S].  We want to
       show that [Gamma |- [x:=v]y : S].

       There are two cases to consider: either [x=y] or [x<>y]. *)
    remember (beq_id x y) as e. destruct e.
    SCase "x=y".
    (* If [x = y], then we know that [U = S], and that [[x:=v]y = v].
       So what we really must show is that if [empty |- v : U] then
       [Gamma |- v : U].  We have already proven a more general version
       of this theorem, called context invariance. *)
      apply beq_id_eq in Heqe. subst.
      unfold extend in H1. rewrite <- beq_id_refl in H1.
      inversion H1; subst. clear H1.
      eapply context_invariance...
      intros x Hcontra.
      destruct (free_in_context _ _ S empty Hcontra) as [T' HT']...
      inversion HT'.
    SCase "x<>y".
    (* If [x <> y], then [Gamma y = Some S] and the substitution has no
       effect.  We can show that [Gamma |- y : S] by [T_Var]. *)
      apply T_Var... unfold extend in H1. rewrite <- Heqe in H1...
  Case "tabs".
    rename i into y. rename t into T11.
    (* If [t = tabs y T11 t0], then we know that
         [Gamma,x:U |- tabs y T11 t0 : T11->T12]
         [Gamma,x:U,y:T11 |- t0 : T12]
         [empty |- v : U]
       As our IH, we know that forall S Gamma,
         [Gamma,x:U |- t0 : S -> Gamma |- [x:=v]t0 S].

       We can calculate that
         [x:=v]t = tabs y T11 (if beq_id x y then t0 else [x:=v]t0)
       And we must show that [Gamma |- [x:=v]t : T11->T12].  We know
       we will do so using [T_Abs], so it remains to be shown that:
         [Gamma,y:T11 |- if beq_id x y then t0 else [x:=v]t0 : T12]
       We consider two cases: [x = y] and [x <> y].
    *)
    apply T_Abs...
    remember (beq_id x y) as e. destruct e.
    SCase "x=y".
    (* If [x = y], then the substitution has no effect.  Context
       invariance shows that [Gamma,y:U,y:T11] and [Gamma,y:T11] are
       equivalent.  Since the former context shows that [t0 : T12], so
       does the latter. *)
      eapply context_invariance...
      apply beq_id_eq in Heqe. subst.
      intros x Hafi. unfold extend.
      destruct (beq_id y x)...
    SCase "x<>y".
    (* If [x <> y], then the IH and context invariance allow us to show that
         [Gamma,x:U,y:T11 |- t0 : T12]       =>
         [Gamma,y:T11,x:U |- t0 : T12]       =>
         [Gamma,y:T11 |- [x:=v]t0 : T12] *)
      apply IHt. eapply context_invariance...
      intros z Hafi. unfold extend.
      remember (beq_id y z) as e0. destruct e0...
      apply beq_id_eq in Heqe0. subst.
      rewrite <- Heqe...
Qed.

Theorem preservation : forall t t' T,
     has_type empty t T  ->
     t ==> t'  ->
     has_type empty t' T.
Proof with eauto.
  intros t t' T HT.
  (* Theorem: If [empty |- t : T] and [t ==> t'], then [empty |- t' : T]. *)
  remember (@empty ty) as Gamma. generalize dependent HeqGamma.
  generalize dependent t'.
  (* Proof: By induction on the given typing derivation.  Many cases are
     contradictory ([T_Var], [T_Abs]).  We show just the interesting ones. *)
  has_type_cases (induction HT) Case;
    intros t' HeqGamma HE; subst; inversion HE; subst...
  Case "T_App".
    (* If the last rule used was [T_App], then [t = t1 t2], and three rules
       could have been used to show [t ==> t']: [ST_App1], [ST_App2], and
       [ST_AppAbs]. In the first two cases, the result follows directly from
       the IH. *)
    inversion HE; subst...
    SCase "ST_AppAbs".
      (* For the third case, suppose
           [t1 = tabs x T11 t12]
         and
           [t2 = v2].
         We must show that [empty |- [x:=v2]t12 : T2].
         We know by assumption that
             [empty |- tabs x T11 t12 : T1->T2]
         and by inversion
             [x:T1 |- t12 : T2]
         We have already proven that substitution_preserves_typing and
             [empty |- v2 : T1]
         by assumption, so we are done. *)
      apply substitution_preserves_typing with T1...
      inversion HT1...

Qed.
(** [] *)

(* ###################################################################### *)
(** *** Determinism *)

Lemma step_deterministic :
   deterministic step.
Proof with eauto.
   unfold deterministic.
   intros t t' t'' E1 E2.
   generalize dependent t''.
   step_cases (induction E1) Case; intros t'' E2; inversion E2; subst; clear E2...
   Case "ST_AppAbs"...
       inversion H2.
       apply ex_falso_quodlibet; apply value__normal in v...
   Case "ST_App1".
       inversion E1.
       f_equal...
       apply ex_falso_quodlibet; apply value__normal in H1...
   Case "ST_App2".
       apply ex_falso_quodlibet; apply value__normal in H2...
       apply ex_falso_quodlibet; apply value__normal in v...
       f_equal...

   Case "ST_IfTrue".
       inversion H3.
   Case "ST_IfFalse".
       inversion H3.
   Case "ST_If".
       inversion E1.
       inversion E1.
       f_equal...
Qed.

(* ###################################################################### *)
(** * Normalization *)

(** Now for the actual normalization proof.

    Our goal is to prove that every well-typed term evaluates to a
    normal form.  In fact, it turns out to be convenient to prove
    something slightly stronger, namely that every well-typed term
    evaluates to a _value_.  This follows from the weaker property
    anyway via the Progress lemma (why?) but otherwise we don't need
    Progress, and we didn't bother re-proving it above.

    Here's the key definition: *)

Definition halts  (t:tm) : Type :=  (exists t' : tm, (t ==>* t') * value t') %type.

(** A trivial fact: *)

Lemma value_halts : forall v, value v -> halts v.
Proof.
  intros v H. unfold halts.
  exists v. split.
  apply multi_refl.
  assumption.
Qed.

(** The key issue in the normalization proof (as in many proofs by
induction) is finding a strong enough induction hypothesis.  To this
end, we begin by defining, for each type [T], a set [R_T] of closed
terms of type [T].  We will specify these sets using a relation [R]
and write [R T t] when [t] is in [R_T]. (The sets [R_T] are sometimes
called _saturated sets_ or _reducibility candidates_.)

Here is the definition of [R] for the base language:

- [R bool t] iff [t] is a closed term of type [bool] and [t] halts in a value

- [R (T1 -> T2) t] iff [t] is a closed term of type [T1 -> T2] and [t] halts
  in a value _and_ for any term [s] such that [R T1 s], we have [R
  T2 (t s)]. *)

(** This definition gives us the strengthened induction hypothesis that we
need.  Our primary goal is to show that all _programs_ ---i.e., all
closed terms of base type---halt.  But closed terms of base type can
contain subterms of functional type, so we need to know something
about these as well.  Moreover, it is not enough to know that these
subterms halt, because the application of a normalized function to a
normalized argument involves a substitution, which may enable more
evaluation steps.  So we need a stronger condition for terms of
functional type: not only should they halt themselves, but, when
applied to halting arguments, they should yield halting results.

The form of [R] is characteristic of the _logical relations_ proof
technique.  (Since we are just dealing with unary relations here, we
could perhaps more properly say _logical predicates_.)  If we want to
prove some property [P] of all closed terms of type [A], we proceed by
proving, by induction on types, that all terms of type [A] _possess_
property [P], all terms of type [A->A] _preserve_ property [P], all
terms of type [(A->A)->(A->A)] _preserve the property of preserving_
property [P], and so on.  We do this by defining a family of
predicates, indexed by types.  For the base type [A], the predicate is
just [P].  For functional types, it says that the function should map
values satisfying the predicate at the input type to values satisfying
the predicate at the output type.

When we come to formalize the definition of [R] in Coq, we hit a
problem.  The most obvious formulation would be as a parameterized
Inductive proposition like this:

Inductive R : ty -> tm -> Prop :=
| R_bool : forall b t, has_type empty t TBool ->
                halts t ->
                R TBool t
| R_arrow : forall T1 T2 t, has_type empty t (TArrow T1 T2) ->
                halts t ->
                (forall s, R T1 s -> R T2 (tapp t s)) ->
                R (TArrow T1 T2) t.

Unfortunately, Coq rejects this definition because it violates the
_strict positivity requirement_ for inductive definitions, which says
that the type being defined must not occur to the left of an arrow in
the type of a constructor argument. Here, it is the third argument to
[R_arrow], namely [(forall s, R T1 s -> R TS (tapp t s))], and
specifically the [R T1 s] part, that violates this rule.  (The
outermost arrows separating the constructor arguments don't count when
applying this rule; otherwise we could never have genuinely inductive
predicates at all!)  The reason for the rule is that types defined
with non-positive recursion can be used to build non-terminating
functions, which as we know would be a disaster for Coq's logical
soundness. Even though the relation we want in this case might be
perfectly innocent, Coq still rejects it because it fails the
positivity test.

Fortunately, it turns out that we _can_ define [R] using a
[Fixpoint]: *)

Fixpoint R (T:ty) (t:tm) {struct T} : Type :=
  (has_type empty t T * (halts t *
  (match T with
   | TBool  => True
   | TArrow T1 T2 => (forall s, R T1 s -> R T2 (tapp t s))

   end))) % type.

(** As immediate consequences of this definition, we have that every
element of every set [R_T] halts in a value and is closed with type
[t] :*)

Lemma R_halts : forall {T} {t}, R T t -> halts t.
Proof.
  intros. destruct T; unfold R in X; inversion X; inversion X1; subst; assumption.
Qed.

Lemma R_typable_empty : forall {T} {t}, R T t -> has_type empty t T.
Proof.
  intros. destruct T; unfold R in X; inversion X; inversion X1; assumption.
Qed.

(** Now we proceed to show the main result, which is that every
well-typed term of type [T] is an element of [R_T].  Together with
[R_halts], that will show that every well-typed term halts in a
value.  *)

(* ###################################################################### *)
(** **  Membership in [R_T] is invariant under evaluation *)

(** We start with a preliminary lemma that shows a kind of strong
preservation property, namely that membership in [R_T] is _invariant_
under evaluation. We will need this property in both directions,
i.e. both to show that a term in [R_T] stays in [R_T] when it takes a
forward step, and to show that any term that ends up in [R_T] after a
step must have been in [R_T] to begin with.

First of all, an easy preliminary lemma. Note that in the forward
direction the proof depends on the fact that our language is
determinstic. This lemma might still be true for non-deterministic
languages, but the proof would be harder! *)

Definition iff (P Q : Type) := ((P -> Q) * (Q -> P)) % type.

Notation "P <-> Q" := (iff P Q)
                      (at level 95, no associativity) : type_scope.

Theorem ex_falso_quodlibet : forall (P:Type),
  False -> P.
Proof.
  intros P contra.
  inversion contra.  Qed.

Lemma step_preserves_halting : forall t t', (t ==> t') -> (halts t <-> halts t').
Proof.
 intros t t' ST.  unfold halts.
 split.
 Case "->".
  intros [t'' [STM V]].
  inversion STM; subst.
   apply ex_falso_quodlibet.  apply value__normal in V. unfold normal_form in V. apply V. exists t'. auto.
   rewrite (step_deterministic _ _ _ ST H). exists t''. split; assumption.
 Case "<-".
  intros [t'0 [STM V]].
  exists t'0. split; eauto.
  eapply multi_step. eassumption. assumption.
Qed.

(** Now the main lemma, which comes in two parts, one for each
   direction.  Each proceeds by induction on the structure of the type
   [T].  In fact, this is where we make fundamental use of the
   finiteness of types.

   One requirement for staying in [R_T] is to stay in type [T]. In the
   forward direction, we get this from ordinary type Preservation. *)

Lemma step_preserves_R : forall T t t', (t ==> t') -> R T t -> R T t'.
Proof.
 induction T;  intros t t' E Rt; unfold R; fold R; unfold R in Rt; fold R in Rt;
               destruct Rt as [typable_empty_t [halts_t RRt]].
  (* TBool *)
  split. eapply preservation; eauto.
  split. apply (step_preserves_halting _ _ E); eauto.
  auto.
  (* TArrow *)
  split. eapply preservation; eauto.
  split. apply (step_preserves_halting _ _ E); eauto.
  intros.
  eapply IHT2.
  apply  ST_App1. apply E.
  apply RRt; auto.

Qed.

(** The generalization to multiple steps is trivial: *)

Lemma multistep_preserves_R : forall T t t',
  (t ==>* t') -> R T t -> R T t'.
Proof.
  intros T t t' STM; induction STM; intros.
  assumption.
  apply IHSTM. eapply step_preserves_R. apply r. assumption.
Qed.

(** In the reverse direction, we must add the fact that [t] has type
   [T] before stepping as an additional hypothesis. *)

Lemma step_preserves_R' : forall T t t',
  has_type empty t T -> (t ==> t') -> R T t' -> R T t.
Proof.
  induction T; intros t t' typable_empty_t E Rt'; unfold R; fold R;
               unfold R in Rt'; fold R in Rt';
               destruct Rt' as [typable_empty_t' [halts_t' RRt']].
  (* TBool *)
  split. assumption.
  split. apply (step_preserves_halting _ _ E); eauto.
  auto.
  (* TArrow *)
  split. assumption.
  split. apply (step_preserves_halting _ _ E); eauto.
  intros.
  eapply IHT2. eapply T_App.  apply typable_empty_t.
  eapply R_typable_empty. assumption.
  apply  ST_App1. apply E.
  apply RRt'; auto.

Qed.

Lemma multistep_preserves_R' : forall T t t',
  has_type empty t T -> (t ==>* t') -> R T t' -> R T t.
Proof.
  intros T t t' HT STM.
  induction STM; intros.
    assumption.
    eapply step_preserves_R'.  assumption. apply r. apply IHSTM.
    eapply preservation;  eauto. auto.
Qed.

(* ###################################################################### *)
(** ** Closed instances of terms of type [T] belong to [R_T] *)

(** Now we proceed to show that every term of type [T] belongs to
[R_T].  Here, the induction will be on typing derivations (it would be
surprising to see a proof about well-typed terms that did not
somewhere involve induction on typing derivations!).  The only
technical difficulty here is in dealing with the abstraction case.
Since we are arguing by induction, the demonstration that a term
[tabs x T1 t2] belongs to [R_(T1->T2)] should involve applying the
induction hypothesis to show that [t2] belongs to [R_(T2)].  But
[R_(T2)] is defined to be a set of _closed_ terms, while [t2] may
contain [x] free, so this does not make sense.

This problem is resolved by using a standard trick to suitably
generalize the induction hypothesis: instead of proving a statement
involving a closed term, we generalize it to cover all closed
_instances_ of an open term [t].  Informally, the statement of the
lemma will look like this:

If [x1:T1,..xn:Tn |- t : T] and [v1,...,vn] are values such that
[R T1 v1], [R T2 v2], ..., [R Tn vn], then
[R T ([x1:=v1][x2:=v2]...[xn:=vn]t)].

The proof will proceed by induction on the typing derivation
[x1:T1,..xn:Tn |- t : T]; the most interesting case will be the one
for abstraction. *)

(* ###################################################################### *)
(** *** Multisubstitutions, multi-extensions, and instantiations *)

(** However, before we can proceed to formalize the statement and
proof of the lemma, we'll need to build some (rather tedious)
machinery to deal with the fact that we are performing _multiple_
substitutions on term [t] and _multiple_ extensions of the typing
context.  In particular, we must be precise about the order in which
the substitutions occur and how they act on each other.  Often these
details are simply elided in informal paper proofs, but of course Coq
won't let us do that. Since here we are substituting closed terms, we
don't need to worry about how one substitution might affect the term
put in place by another.  But we still do need to worry about the
_order_ of substitutions, because it is quite possible for the same
identifier to appear multiple times among the [x1,...xn] with
different associated [vi] and [Ti].

To make everything precise, we will assume that environments are
extended from left to right, and multiple substitutions are performed
from right to left.  To see that this is consistent, suppose we have
an environment written as [...,y:bool,...,y:nat,...]  and a
corresponding term substitution written as [...[y:=(tbool
true)]...[y:=(tnat 3)]...t].  Since environments are extended from
left to right, the binding [y:nat] hides the binding [y:bool]; since
substitutions are performed right to left, we do the substitution
[y:=(tnat 3)] first, so that the substitution [y:=(tbool true)] has
no effect. Substitution thus correctly preserves the type of the term.

With these points in mind, the following definitions should make sense.

A _multisubstitution_ is the result of applying a list of
substitutions, which we call an _environment_. *)

Definition env := list (id * tm).

Fixpoint msubst (ss:env) (t:tm) {struct ss} : tm :=
match ss with
| nil => t
| ((x,s)::ss') => msubst ss' ([x:=s]t)
end.

(** We need similar machinery to talk about repeated extension of a
    typing context using a list of (identifier, type) pairs, which we
    call a _type assignment_. *)

Definition tass := list (id * ty).

Fixpoint mextend (Gamma : context) (xts : tass) :=
  match xts with
  | nil => Gamma
  | ((x,v)::xts') => extend (mextend Gamma xts') x v
  end.

(** We will need some simple operations that work uniformly on
environments and type assigments *)

Fixpoint lookup {X:Set} (k : id) (l : list (id * X)) {struct l} : option X :=
  match l with
    | nil => None
    | (j,x) :: l' =>
      if beq_id j k then Some x else lookup k l'
  end.

Fixpoint drop {X:Set} (n:id) (nxs:list (id * X)) {struct nxs} : list (id * X) :=
  match nxs with
    | nil => nil
    | ((n',x)::nxs') => if beq_id n' n then drop n nxs' else (n',x)::(drop n nxs')
  end.

(** An _instantiation_ combines a type assignment and a value
   environment with the same domains, where corresponding elements are
   in R *)

Inductive instantiation :  tass -> env -> Type :=
| V_nil : instantiation nil nil
| V_cons : forall x T v c e, value v -> R T v -> instantiation c e -> instantiation ((x,T)::c) ((x,v)::e).

(** We now proceed to prove various properties of these definitions. *)

(* ###################################################################### *)
(** *** More Substitution Facts *)

(** First we need some additional lemmas on (ordinary) substitution. *)

Lemma vacuous_substitution : forall  t x,
     (appears_free_in x t -> False)  ->
     forall t', [x:=t']t = t.
Proof with eauto.
  t_cases (induction t) Case; intros; simpl.
  Case "tvar".
    remember (beq_id x i) as e. destruct e...
      destruct H. apply beq_id_eq in Heqe. subst...
  Case "tapp".
    rewrite IHt1... rewrite IHt2...
  Case "tabs".
    remember (beq_id x i) as e. destruct e...
       symmetry in Heqe; apply beq_id_false_not_eq in Heqe.
         rewrite IHt...

  Case "ttrue"...
  Case "tfalse"...
  Case "tif".
    rewrite IHt1... rewrite IHt2... rewrite IHt3...
Qed.

Lemma subst_closed: forall t,
     closed t  ->
     forall x t', [x:=t']t = t.
Proof.
  intros. apply vacuous_substitution. apply H.  Qed.

Lemma subst_not_afi : forall t x v, closed v -> (appears_free_in x ([x:=v]t) -> False).
Proof with eauto.  (* rather slow this way *)
  unfold closed, not.
  t_cases (induction t) Case; intros x v P A; simpl in A.
    Case "tvar".
     remember (beq_id x i) as e; destruct e...
       inversion A; subst. rewrite <- beq_id_refl in Heqe; inversion Heqe.
    Case "tapp".
     inversion A; subst...
    Case "tabs".
     remember (beq_id x i) as e; destruct e...
       apply beq_id_eq in Heqe; subst. inversion A; subst...
       inversion A; subst...

    Case "ttrue".
     inversion A.
    Case "tfalse".
     inversion A.
    Case "tif".
     inversion A; subst...
Qed.

Lemma duplicate_subst : forall t' x t v,
  closed v -> [x:=t]([x:=v]t') = [x:=v]t'.
Proof.
  intros. eapply vacuous_substitution. apply subst_not_afi.  auto.
Qed.

Lemma swap_subst : forall t x x1 v v1, x <> x1 -> closed v -> closed v1 ->
                   [x1:=v1]([x:=v]t) = [x:=v]([x1:=v1]t).
Proof with eauto.
 t_cases (induction t) Case; intros; simpl.
  Case "tvar".
   remember (beq_id x i) as e; destruct e; remember (beq_id x1 i) as e; destruct e.
      apply  beq_id_eq in Heqe. apply beq_id_eq in Heqe0. subst.
         apply ex_falso_quodlibet...
      apply beq_id_eq in Heqe; subst.  simpl.
         rewrite <- beq_id_refl.  apply subst_closed...
      apply beq_id_eq in Heqe0; subst.  simpl.
         rewrite <- beq_id_refl. rewrite subst_closed...
      simpl. rewrite <- Heqe. rewrite <- Heqe0...
  Case "tapp".
   rewrite IHt1...  rewrite IHt2...
  Case "tabs".
   destruct (beq_id x i); destruct (beq_id x1 i)...
     rewrite IHt...

  Case "ttrue"...
  Case "tfalse"...
  Case "tif".
   f_equal...
Qed.

(* ###################################################################### *)
(** *** Properties of multi-substitutions *)

Lemma msubst_closed: forall t, closed t -> forall ss, msubst ss t = t.
Proof.
  induction ss.
    reflexivity.
    destruct a. simpl. rewrite subst_closed; assumption.
Qed.

(** Closed environments are those that contain only closed terms. *)

Fixpoint closed_env (env:env) {struct env} :=
match env with
| nil => True
| (x,t)::env' => closed t /\ closed_env env'
end.

(** Next come a series of lemmas charcterizing how [msubst] of closed terms
    distributes over [subst] and over each term form *)

Lemma subst_msubst: forall env x v t, closed v -> closed_env env ->
  msubst env ([x:=v]t) = [x:=v](msubst (drop x env) t).
Proof.
  induction env0; intros.
    auto.
    destruct a. simpl.
    inversion H0. fold closed_env in H2.
    remember (beq_id i x) as e; destruct e.
      apply  beq_id_eq in Heqe; subst.
        rewrite duplicate_subst; auto.
      symmetry in Heqe. apply beq_id_false_not_eq in Heqe.
      simpl. rewrite swap_subst; eauto.
Qed.

Lemma msubst_var:  forall ss x, closed_env ss ->
   msubst ss (tvar x) =
   match lookup x ss with
   | Some t => t
   | None => tvar x
  end.
Proof.
  induction ss; intros.
    reflexivity.
    destruct a.
     simpl. destruct (beq_id i x).
      apply msubst_closed. inversion H; auto.
      apply IHss. inversion H; auto.
Qed.

Lemma msubst_abs: forall ss x T t,
  msubst ss (tabs x T t) = tabs x T (msubst (drop x ss) t).
Proof.
  induction ss; intros.
    reflexivity.
    destruct a.
      simpl. destruct (beq_id i x); simpl; auto.
Qed.

Lemma msubst_app : forall ss t1 t2, msubst ss (tapp t1 t2) = tapp (msubst ss t1) (msubst ss t2).
Proof.
 induction ss; intros.
   reflexivity.
   destruct a.
    simpl. rewrite <- IHss. auto.
Qed.

(** You'll need similar functions for the other term constructors. *)

(* FILL IN HERE *)

Lemma msubst_true : forall ss, msubst ss ttrue = ttrue.
Proof.
  induction ss; intros.
    auto.
    destruct a.
       simpl. auto.
Qed.

Lemma msubst_false : forall ss, msubst ss tfalse = tfalse.
Proof.
  induction ss; intros.
    auto.
    destruct a.
       simpl. auto.
Qed.

Lemma msubst_if : forall ss t0 t1 t2,
  msubst ss (tif t0 t1 t2) = tif (msubst ss t0) (msubst ss t1) (msubst ss t2).
Proof.
   induction ss; intros.
     auto.
     destruct a. simpl. auto.
Qed.

(* ###################################################################### *)
(** *** Properties of multi-extensions *)

(** We need to connect the behavior of type assignments with that of their
   corresponding contexts. *)

Lemma mextend_lookup : forall (c : tass) (x:id), lookup x c = (mextend empty c) x.
Proof.
  induction c; intros.
    auto.
    destruct a. unfold lookup, mextend, extend. destruct (beq_id i x); auto.
Qed.

Lemma mextend_drop : forall (c: tass) Gamma x x',
       mextend Gamma (drop x c) x' = if beq_id x x' then Gamma x' else mextend Gamma c x'.
   induction c; intros.
      destruct (beq_id x x'); auto.
      destruct a. simpl.
      remember (beq_id i x) as e; destruct e.
        apply beq_id_eq in Heqe; subst. rewrite IHc.
            remember (beq_id x x') as e; destruct e.  auto. unfold extend. rewrite <- Heqe. auto.
        simpl.  unfold extend.  remember (beq_id i x') as e; destruct e.
            apply beq_id_eq in Heqe0; subst.
                              remember (beq_id x x') as e; destruct e.
                  apply beq_id_eq in Heqe0; subst.  rewrite <- beq_id_refl in Heqe.  inversion Heqe.
                  auto.
            auto.
Qed.

(* ###################################################################### *)
(** *** Properties of Instantiations *)

(** These are strightforward. *)

Lemma instantiation_domains_match: forall {c} {e},
  instantiation c e -> forall {x} {T}, lookup x c = Some T -> exists t, lookup x e = Some t.
Proof.
  intros c e V. induction V; intros x0 T0 C.
    solve by inversion .
    simpl in *.
    destruct (beq_id x x0); eauto.
Qed.

Lemma instantiation_env_closed : forall c e,  instantiation c e -> closed_env e.
Proof.
  intros c e V; induction V; intros.
    econstructor.
    unfold closed_env. fold closed_env.
    split.  eapply typable_empty__closed. eapply R_typable_empty. eauto.
        auto.
Qed.

Lemma instantiation_R : forall c e, instantiation c e ->
                        forall x t T, lookup x c = Some T ->
                                      lookup x e = Some t -> R T t.
Proof.
  intros c e V. induction V; intros x' t' T' G E.
    solve by inversion.
    unfold lookup in *.  destruct (beq_id x x').
      inversion G; inversion E; subst.  auto.
      eauto.
Qed.

Lemma instantiation_drop : forall c env,
  instantiation c env -> forall x, instantiation (drop x c) (drop x env).
Proof.
  intros c e V. induction V.
    intros.  simpl.  constructor.
    intros. unfold drop. destruct (beq_id x x0); auto. constructor; eauto.
Qed.

(* ###################################################################### *)
(** *** Congruence lemmas on multistep *)

(** We'll need just a few of these; add them as the demand arises. *)

Lemma multistep_App2 : forall v t t',
  value v -> (t ==>* t') -> (tapp v t) ==>* (tapp v t').
Proof.
  intros v t t' V STM. induction STM.
   apply multi_refl.
   eapply multi_step.
     apply ST_App2; eauto.  auto.
Qed.

Lemma multistep_If : forall t1 t1' t2 t3,
  (t1 ==>* t1') -> (tif t1 t2 t3) ==>* (tif t1' t2 t3).
Proof.
  intros t1 t1' t2 t3 STM. induction STM.
  apply multi_refl.
  eapply multi_step.
  apply ST_If; eauto. auto.
Qed.

(* FILL IN HERE *)

(* ###################################################################### *)
(** *** The R Lemma. *)

(** We finally put everything together.

    The key lemma about preservation of typing under substitution can
    be lifted to multi-substitutions: *)

Lemma msubst_preserves_typing : forall c e,
     instantiation c e ->
     forall Gamma t S, has_type (mextend Gamma c) t S ->
     has_type Gamma (msubst e t) S.
Proof.
  induction 1; intros.
    simpl in X. simpl. auto.
    simpl in X0.  simpl.
    apply IHX.
    eapply substitution_preserves_typing; eauto.
    apply (R_typable_empty r).
Qed.

Theorem multi_trans :
  forall (X:Type) (R: relation X) (x y z : X),
      multi R x y  ->
      multi R y z ->
      multi R x z.
Proof.
  intros X R x y z G H.
  multi_cases (induction G) Case.
    Case "multi_refl". assumption.
    Case "multi_step".
      apply multi_step with y. assumption.
      apply IHG. assumption.  Qed.

Theorem multi_R : forall (X:Type) (R:relation X) (x y : X),
       R x y -> multi R x y.
Proof.
  intros X R x y r.
  apply multi_step with y. apply r. apply multi_refl.   Qed.

(** And at long last, the main lemma. *)

Lemma msubst_R : forall c env t T,
  has_type (mextend empty c) t T -> instantiation c env -> R T (msubst env t).
Proof.
  intros c env0 t T HT V.
  generalize dependent env0.
  (* We need to generalize the hypothesis a bit before setting up the induction. *)
  remember (mextend empty c) as Gamma.
  assert (forall x, Gamma x = lookup x c).
    intros. rewrite HeqGamma. rewrite mextend_lookup. auto.
  clear HeqGamma.
  generalize dependent c.
  has_type_cases (induction HT) Case; intros.

  Case "T_Var".
   rewrite H in e. destruct (instantiation_domains_match V e) as [t P].
   eapply instantiation_R; eauto.
   rewrite msubst_var.  rewrite P. auto. eapply instantiation_env_closed; eauto.

  Case "T_Abs".
    rewrite msubst_abs.
    (* We'll need variants of the following fact several times, so its simplest to
       establish it just once. *)
    assert (WT: has_type empty (tabs x T11 (msubst (drop x env0) t12)) (TArrow T11 T12)).
     eapply T_Abs. eapply msubst_preserves_typing.  eapply instantiation_drop; eauto.
      eapply context_invariance.  apply HT.
      intros.
      unfold extend. rewrite mextend_drop. remember (beq_id x x0) as e; destruct e.  auto.
        rewrite H.
          clear - c Heqe. induction c.
              simpl.  rewrite <- Heqe.  auto.
              simpl. destruct a.  unfold extend. destruct (beq_id i x0); auto.
    unfold R. fold R. split.
       auto.
     split. apply value_halts. apply v_abs.
     intros.
     destruct (R_halts X) as [v [P Q]].
     pose proof (multistep_preserves_R _ _ _ P X).
     apply multistep_preserves_R' with (msubst ((x,v)::env0) t12).
       eapply T_App. eauto.
       apply R_typable_empty; auto.
       eapply multi_trans.  eapply multistep_App2; eauto.
       eapply multi_R.
       simpl.  rewrite subst_msubst.
       eapply ST_AppAbs; eauto.
       eapply typable_empty__closed.
       apply (R_typable_empty X0).
       eapply instantiation_env_closed; eauto.
       eapply (IHHT ((x,T11)::c)).
          intros. unfold extend, lookup. destruct (beq_id x x0); auto.
       constructor; auto.

  Case "T_App".
    rewrite msubst_app.
    destruct (IHHT1 c H env0 V) as [_ [_ P1]].
    pose proof (IHHT2 c H env0 V) as P2.  fold R in P1.  auto.

  Case "T_True".
    rewrite msubst_true.
    unfold R. split.
    apply T_True.
    split.  unfold halts.  exists ttrue. split. apply multi_refl. apply v_true. auto.

  Case "T_False".
    rewrite msubst_false.
    unfold R. split.
    apply T_False.
    split.  unfold halts.  exists tfalse. split. apply multi_refl. apply v_false. auto.

  Case "T_If".
    rewrite msubst_if.
    assert (WT: has_type empty (tif (msubst env0 t0) (msubst env0 t1) (msubst env0 t2)) T).
      apply T_If; eapply msubst_preserves_typing; eauto;
        eapply context_invariance; eauto; intros; rewrite <- mextend_lookup;  auto.
    pose proof (IHHT1 c H env0 V) as IH1.
    destruct (R_halts IH1) as [v [P Q]].
    assert (R TBool v).
        eapply multistep_preserves_R. apply P. apply IH1.
   (* The following is a somewhat easier approach than that taken in Pierce's TAPL
      sample solutions; in essence we apply canonical forms, on the fly *)
   pose proof (R_typable_empty X).
   inversion Q; subst.
      (* abs : impossible *)
      inversion X0.

      (* pair : impossible *)
      inversion X0.

      (* true *)
      eapply multistep_preserves_R' with (msubst env0 t1).
      assumption.
      eapply multi_trans. apply multistep_If. eapply P.
      eapply multi_R. apply ST_IfTrue.
      apply (IHHT2 c H env0 V).

      (* false *)
      eapply multistep_preserves_R' with (msubst env0 t2).
      assumption.
      eapply multi_trans. apply multistep_If. eapply P.
      eapply multi_R. apply ST_IfFalse.
      apply (IHHT3 c H env0 V).
Qed.

(* ###################################################################### *)
(** *** Normalization Theorem *)

Theorem normalization : forall t T, has_type empty t T -> halts t.
Proof.
  intros.
  replace t with (msubst nil t).
  eapply R_halts.
  eapply msubst_R; eauto. instantiate (2:= nil). eauto.
  eapply V_nil.
  auto.
Qed.

(** * MoreStlc: A Typechecker for STLC *)

(* $Date: 2012-04-16 14:02:51 -0400 (Mon, 16 Apr 2012) $ *)

(** The [has_type] relation of the STLC defines what it means for a
    term to belong to a type (in some context).  But it doesn't, by
    itself, tell us how to _check_ whether or not a term is well
    typed.

    Fortunately, the rules defining [has_type] are _syntax directed_
    -- they exactly follow the shape of the term.  This makes it
    straightforward to translate the typing rules into clauses of a
    typechecking _function_ that takes a term and a context and either
    returns the term's type or else signals that the term is not
    typable. *)

(* ###################################################################### *)
(** ** Comparing Types *)

(** First, we need a function to compare two types for equality... *)

Fixpoint beq_ty (T1 T2:ty) : bool :=
  match T1,T2 with
  | TBool, TBool =>
      true
  | TArrow T11 T12, TArrow T21 T22 =>
      andb (beq_ty T11 T21) (beq_ty T12 T22)

  | _,_ =>
      false
  end.

(** ... and we need to establish the usual two-way connection between
    the boolean result returned by [beq_ty] and the logical
    proposition that its inputs are equal. *)

Lemma beq_ty_refl : forall T1,
  beq_ty T1 T1 = true.
Proof.
  intros T1. induction T1; simpl.
    reflexivity.
    rewrite IHT1_1. rewrite IHT1_2. reflexivity.

Qed.

Lemma beq_ty__eq : forall T1 T2,
  beq_ty T1 T2 = true -> T1 = T2.
Proof with auto.
  intros T1. induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq.
  Case "T1=TBool".
    reflexivity.
  Case "T1=TArrow T1_1 T1_2".
    apply andb_true in H0. inversion H0 as [Hbeq1 Hbeq2].
    apply IHT1_1 in Hbeq1. apply IHT1_2 in Hbeq2. subst...

Qed.

(* ###################################################################### *)
(** ** The Typechecker *)

(** Now here's the typechecker.  It works by walking over the
    structure of the given term, returning either [Some T] or [None].
    Each time we make a recursive call to find out the types of the
    subterms, we need to pattern-match on the results to make sure
    that they are not [None].  Also, in the [tapp] case, we use
    pattern matching to extract the left- and right-hand sides of the
    function's arrow type (and fail if the type of the function is not
    [TArrow T11 T12] for some [T1] and [T2]). *)

Fixpoint type_check (Gamma:context) (t:tm) : option ty :=
  match t with
  | tvar x => Gamma x
  | tabs x T11 t12 => match type_check (extend Gamma x T11) t12 with
                          | Some T12 => Some (TArrow T11 T12)
                          | _ => None
                        end
  | tapp t1 t2 => match type_check Gamma t1, type_check Gamma t2 with
                      | Some (TArrow T11 T12),Some T2 =>
                        if beq_ty T11 T2 then Some T12 else None
                      | _,_ => None
                    end
  | ttrue => Some TBool
  | tfalse => Some TBool
  | tif x t f => match type_check Gamma x with
                     | Some TBool =>
                       match type_check Gamma t, type_check Gamma f with
                         | Some T1, Some T2 =>
                           if beq_ty T1 T2 then Some T1 else None
                         | _,_ => None
                       end
                     | _ => None
                   end

  end.

(* ###################################################################### *)
(** ** Properties *)

(** To verify that this typechecking algorithm is the correct one, we
    show that it is _sound_ and _complete_ for the original [has_type]
    relation -- that is, [type_check] and [has_type] define the same
    partial function. *)

Theorem type_checking_sound : forall Gamma t T,
  type_check Gamma t = Some T -> has_type Gamma t T.
Proof with eauto.
  intros Gamma t. generalize dependent Gamma.
  t_cases (induction t) Case; intros Gamma T Htc; inversion Htc; clear Htc.
  Case "tvar"...
  Case "tapp".
    remember (type_check Gamma t1) as TO1.
    remember (type_check Gamma t2) as TO2.
    destruct TO1 as [T1|]; try solve by inversion;

    destruct T1 as [|T11 T12]; try solve by inversion.
    destruct TO2 as [T2|]; try solve by inversion.
    remember (beq_ty T11 T2) as b.
    destruct b; try solve by inversion.
    symmetry in Heqb. apply beq_ty__eq in Heqb.
    inversion H0; subst...
  Case "tabs".
    rename i into y. rename t into T1.
    remember (extend Gamma y T1) as G'.
    remember (type_check G' t0) as TO2.
    destruct TO2; try solve by inversion.
    inversion H0; subst...

  Case "ttrue"...
  Case "tfalse"...
  Case "tif".
    remember (type_check Gamma t1) as TOc.
    remember (type_check Gamma t2) as TO1.
    remember (type_check Gamma t3) as TO2.
    destruct TOc as [Tc|]; try solve by inversion.
    destruct Tc; try solve by inversion.
    destruct TO1 as [T1|]; try solve by inversion.
    destruct TO2 as [T2|]; try solve by inversion.
    remember (beq_ty T1 T2) as b.
    destruct b; try solve by inversion.
    symmetry in Heqb. apply beq_ty__eq in Heqb.
    inversion H0. subst. subst...
Qed.

Theorem type_checking_complete : forall Gamma t T,
  has_type Gamma t T -> type_check Gamma t = Some T.
Proof with auto.
  intros Gamma t T Hty.
  has_type_cases (induction Hty) Case; simpl.
  Case "T_Var"...
  Case "T_Abs". rewrite IHHty...
  Case "T_App".
    rewrite IHHty1. rewrite IHHty2.
    rewrite (beq_ty_refl T1)...

  Case "T_True"...
  Case "T_False"...
  Case "T_If". rewrite IHHty1. rewrite IHHty2.
    rewrite IHHty3. rewrite (beq_ty_refl T)...
Qed.


Require Import Arith Util EqDec List.
Require Import Containers.OrderedTypeEx Integers.

Set Implicit Arguments.

(** * More or less abstract values *)
(** A file that abstacts over values and (should) provide all necessary operations. Although we concretely instantiate val to int, we maintain this file as interface between our proofs and Integer library. *)

(** Make the value type bitvectors and the default value 0 as a bitvector **)
Definition val := int.
Definition default_val : val := Int.zero.

Instance inst_val_defaulted : Defaulted val := {
  default_el := default_val
}.

Definition val_zero : val := Int.zero.
Definition val_one : val := Int.one.

Instance inst_eq_dec_val : EqDec val eq.
hnf; intros. eapply Int.eq_dec.
Defined.

Inductive binop : Type :=
| BinOpAdd
| BinOpSub
| BinOpMul
| BinOpDiv
| BinOpEq
| BinOpLt
| BinOpLe
| BinOpGt
| BinOpGe.

Instance inst_eq_dec_binop : EqDec binop eq.
Proof.
  hnf; intros. change ({x = y} + {x <> y}).
  decide equality.
Qed.

Inductive unop : Type :=
| UnOpToBool
| UnOpNot
| UnOpNeg.

Instance inst_eq_dec_unop : EqDec unop eq.
Proof.
  hnf; intros. change ({x = y} + {x <> y}).
  decide equality.
Qed.

Declare ML Module "containers_plugin".
Generate OrderedType unop.
Generate OrderedType binop.

Lemma unop_eq_eq x y
  : unop_eq x y -> x = y.
Proof.
  destruct x,y; inversion 1; eauto.
Qed.

Lemma binop_eq_eq x y
  : binop_eq x y -> x = y.
Proof.
  destruct x,y; inversion 1; eauto.
Qed.

Require Coq.Structures.OrderedTypeEx.

Instance Reflexive_eq_int : Reflexive Int.eq.
Proof.
  hnf; intros. hnf. cases; eauto.
  rewrite Int.eq_true in Heq. congruence.
Qed.

Instance Symmetric_eq_int : Symmetric Int.eq.
Proof.
  hnf; intros. rewrite Int.eq_sym; eauto.
Qed.

Instance Transitive_eq_int : Transitive Int.eq.
Proof.
  hnf; intros.
  pose proof (Int.eq_spec x y).
  pose proof (Int.eq_spec y z).
  cases in H1; cases in H2; subst; eauto.
Qed.

Instance Equivalence_eq_int : Equivalence Int.eq.
Proof.
  econstructor; eauto with typeclass_instances.
Qed.

Definition int_eq x y := Int.intval x = Int.intval y.

Instance Reflexive_eq_int' : Reflexive int_eq.
Proof.
  hnf; intros. hnf. reflexivity.
Qed.

Instance Symmetric_eq_int' : Symmetric int_eq.
Proof.
  unfold int_eq. hnf; intros. symmetry; eauto.
Qed.

Instance Transitive_eq_int' : Transitive int_eq.
Proof.
  unfold int_eq. hnf; intros. etransitivity; eauto.
Qed.

Instance Equivalence_eq_int' : Equivalence int_eq.
Proof.
  econstructor; eauto with typeclass_instances.
Qed.

Instance Transitive_lt_int : Transitive Int.ltu.
Proof.
  hnf. unfold Int.ltu. intros ? ? ? A B.
  cases in A; invc A; eauto.
  cases in B; invc B; eauto.
  destruct Z_StrictOrder.
  specialize (StrictOrder_Transitive _ _ _ l l0).
  rewrite Coqlib.zlt_true; eauto.
Qed.

Instance Irreflexive_lt_int : Irreflexive Int.ltu.
Proof.
  unfold Irreflexive, complement, Reflexive, Int.ltu; intros.
  cases in H; eauto.
  eapply Z.lt_irrefl; eauto.
Qed.

Instance int_eq_eq_lt
  : Proper (int_eq ==> int_eq ==> eq) Int.ltu.
Proof.
  unfold Proper, respectful, Int.ltu, Int.unsigned, int_eq; intros.
  rewrite H, H0. eauto.
Qed.

Instance StrictOrder_lt_int : StrictOrder Int.ltu eq.
Proof.
  econstructor; eauto with typeclass_instances.
  - intros ? ? LE EQ.
    rewrite <- EQ in LE.
    eapply (Irreflexive_lt_int x); eauto.
Defined.

Definition int_compare (x y : int) : Datatypes.comparison :=
  Z.compare (Int.intval x) (Int.intval y).

Unset Printing Records.

Instance EqDecDatatypescomparison
  : EqDec Datatypes.comparison eq.
Proof.
  hnf; intros.
  destruct x,y;
    try (now (left; reflexivity));
    try now (right; hnf; intros H; inv H).
Qed.

Lemma compare_spec_int x y
  : compare_spec eq Int.ltu x y (int_compare x y).
Proof.
  pose proof (Z.compare_spec (Int.intval x) (Int.intval y)).
  case_eq (int_compare x y); intros EQ; econstructor; unfold int_compare in EQ;
    rewrite EQ in H; inv H; eauto.
  - destruct x,y; simpl in *; subst.
    f_equal. destruct intrange, intrange0.
    f_equal. Unset Printing Notations.
    eapply dec_UIP. eauto with typeclass_instances.
    eapply dec_UIP. eauto with typeclass_instances.
  - hnf. unfold Int.ltu.
    rewrite Coqlib.zlt_true; eauto.
  - hnf. unfold Int.ltu.
    rewrite Coqlib.zlt_true; eauto.
Qed.

Lemma compare_spec_int_eq x y
  : int_compare x y = Eq -> x = y.
Proof.
  intros.
  pose proof (compare_spec_int x y). rewrite H in H0.
  inv H0. eauto.
Qed.

Instance int_eq_dec : EqDec val int_eq.
hnf; intros. destruct x,y.
eapply Z.eq_dec.
Defined.

Instance int_eq_dec' x y : Computable (int_eq x y).
hnf; intros. destruct x,y.
eapply Z.eq_dec.
Defined.

Lemma int_eq_eq x y
  : int_eq x y -> x = y.
Proof.
  unfold int_eq; destruct x,y; simpl; intros; subst.
  eapply Integers.Int.mkint_eq. reflexivity.
Qed.

Hint Resolve int_eq_eq.

Smpl Add 100
     match goal with
     | [ H : int_eq _ _ |- _ ] => eapply int_eq_eq in H
     end : inv_trivial.

Instance OrderedType_int : OrderedType int.
Proof.
  eapply (Build_OrderedType _ eq Int.ltu); eauto with typeclass_instances.
  eapply compare_spec_int.
Defined.

Definition option_lift1 A B (f:A -> B) := fun x => Some (f x).
Definition option_lift2 A B C (f:A -> B -> C) := fun x y => Some (f x y).

Definition val_true := Int.one.
Definition val_false := Int.zero.

Lemma val_true_false_neq
  : val_true <> val_false.
Proof.
  eapply Int.one_not_zero.
Qed.

Lemma val_true_false_nequiv
  : val_true =/= val_false.
Proof.
  inversion 1.
Qed.

Definition bool2val (b:bool) :=
  match b with
  | true => val_true
  | false => val_false
  end.

Definition val2bool (v: val) : bool := if [ v = val_zero ] then false else true.

Lemma val2bool_true
: val2bool val_true = true.
Proof.
  unfold val2bool.
  cases; eauto.
  exfalso; eauto using val_true_false_neq.
Qed.

Lemma val2bool_false
: val2bool val_false = false.
Proof.
  unfold val2bool.
  cases; eauto.
Qed.

Lemma val2bool_bool2val b
  : val2bool (bool2val b) = b.
Proof.
  destruct b; simpl; reflexivity.
Qed.

Definition binop_eval (o:binop) :=
  match o with
      | BinOpAdd => option_lift2 Int.add
      | BinOpSub => option_lift2 Int.sub
      | BinOpMul => option_lift2 Int.mul
      | BinOpDiv => fun x y =>
                     if [ y = val_zero \/
                          (x = (Int.repr Int.min_signed) /\ y = Int.mone)]
                     then None else (Some (Int.divs x y))
      | BinOpEq => option_lift2 (fun x y => bool2val(Int.eq x y))
      | BinOpLt => option_lift2 (fun x y => bool2val(Int.lt x y))
      | BinOpLe => option_lift2 (fun x y => bool2val(negb (Int.lt y x)))
      | BinOpGt => option_lift2 (fun x y => bool2val(Int.lt y x))
      | BinOpGe => option_lift2 (fun x y => bool2val(negb (Int.lt x y)))
    end.

Lemma binop_eval_div_zero x y
  : y = val_zero \/ (x = (Int.repr Int.min_signed) /\ y = Int.mone)
    <-> binop_eval BinOpDiv x y = None.
Proof.
  intros; simpl; cases; split; intros; eauto; exfalso; try congruence.
  eapply NOTCOND. eauto.
Qed.

Lemma binop_eval_div_nonzero x y
  : (y <> val_zero /\ (x <> (Int.repr Int.min_signed) \/ y <> Int.mone))
    -> exists v, binop_eval BinOpDiv x y = Some v.
Proof.
  intros; simpl; cases; eauto.
  firstorder.
Qed.

Lemma binop_eval_not_div op x y
  : op <> BinOpDiv
    -> exists v, binop_eval op x y = Some v.
Proof.
  intros; destruct op; simpl; unfold option_lift2; eauto.
  congruence.
Qed.

Definition unop_eval (o:unop) :=
  match o with
  | UnOpToBool => option_lift1 (fun a => bool2val(val2bool a))
  | UnOpNot => option_lift1 Int.notbool
  | UnOpNeg => option_lift1 Int.neg
  end
.
Lemma unop_eval_total op x
  : exists v, unop_eval op x = Some v.
Proof.
  intros; destruct op; simpl; unfold option_lift1; eauto.
Qed.

(*
Lemma binop_eval_equiv
  : Proper (eq ==> equiv ==> equiv ==> equiv ) binop_eval.
Proof.
  unfold Proper, respectful; intros; subst.
  destruct y, x0,x1,y0,y1; compute in H0, H1; subst; simpl; unfold option_lift2;
    try reflexivity.
Qed.

Lemma unop_eval_equiv
  : Proper (eq ==> equiv ==> equiv ) unop_eval.
Proof.
  unfold Proper, respectful; intros; subst.
  destruct y, x0,y0; compute in H0; subst; simpl; unfold option_lift1;
    try reflexivity.
Qed.

Lemma unop_eval_equiv'
  : Proper (equiv ==> equiv ==> equiv ) unop_eval.
Proof.
  unfold Proper, respectful; intros; subst.
  destruct x0,y0; inv H; compute in H0; subst; simpl; unfold option_lift1;
    try reflexivity.
Qed.
 *)

Opaque val.
Opaque default_val.
Opaque val_true.
Opaque val_false.
Opaque val_zero.
Opaque val2bool.

Lemma int_eq_true_false_absurd
  : int_eq val_true val_false -> False.
Proof.
  intros. eapply int_eq_eq in H. inv H.
Qed.

Smpl Add 100
     match goal with
     | [ H : @Equivalence.equiv val int_eq Equivalence_eq_int' _ _ |- _ ] =>
       eapply int_eq_eq in H
     end : inv_trivial.

Smpl Add match goal with
         | [ H : int_eq val_true val_false |- _ ] =>
           exfalso; eapply int_eq_true_false_absurd in H; eauto
         | [ H : val_true = val_false |- _ ] => inv H
         | [ H : val_false = val_true |- _ ] => inv H
         | [ H : val_true === val_false |- _ ] => inv H
         | [ H : val_false === val_true |- _ ] => inv H
         end : inv_trivial.

Instance int_eq_trans : Transitive (int_eq).
Proof.
  hnf; intros. rewrite H ;eauto.
Qed.

Instance int_eq_sym : Symmetric (int_eq).
Proof.
  hnf; intros. rewrite H ;eauto. reflexivity.
Qed.