(*************************************************************)
(*      This file is distributed under the terms of the      *)
(*      GNU Lesser General Public License Version 2.1        *)
(*************************************************************)
(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)
(*************************************************************)

(***********************************************************************
    Summation.v from Z to Z
 *********************************************************************)
Require Import Arith.
Require Import ArithRing.
Require Import ListAux.
Require Import ZArith.
Require Import Iterator.
Require Import ZProgression.

Open Scope Z_scope.
(* Iterated Sum *)

Definition Zsum :=
   fun n m f =>
   if Zle_bool n m
     then iter 0 f Zplus (progression Zsucc n (Zabs_nat ((1 + m) - n)))
     else iter 0 f Zplus (progression Zpred n (Zabs_nat ((1 + n) - m))).
Hint Unfold Zsum .

Lemma Zsum_nn: forall n f,  Zsum n n f = f n.
intros n f; unfold Zsum; rewrite Zle_bool_refl.
replace ((1 + n) - n) with 1; auto with zarith.
simpl; ring.
Qed.

Theorem permutation_rev: forall (A:Set) (l : list A),  permutation (rev l) l.
intros a l; elim l; simpl; auto.
intros a1 l1 Hl1.
apply permutation_trans with (cons a1 (rev l1)); auto.
change (permutation (rev l1 ++ (a1 :: nil)) (app (cons a1 nil) (rev l1))); auto.
Qed.

Lemma Zsum_swap: forall (n m : Z) (f : Z ->  Z),  Zsum n m f = Zsum m n f.
intros n m f; unfold Zsum.
generalize (Zle_cases n m) (Zle_cases m n); case (Zle_bool n m);
 case (Zle_bool m n); auto with arith.
intros; replace n with m; auto with zarith.
3:intros H1 H2; contradict H2; auto with zarith.
intros H1 H2; apply iter_permutation; auto with zarith.
apply permutation_trans
     with (rev (progression Zsucc n (Zabs_nat ((1 + m) - n)))).
apply permutation_sym; apply permutation_rev.
rewrite Zprogression_opp; auto with zarith.
replace (n + Z_of_nat (pred (Zabs_nat ((1 + m) - n)))) with m; auto.
replace (Zabs_nat ((1 + m) - n)) with (S (Zabs_nat (m - n))); auto with zarith.
simpl.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
replace ((1 + m) - n) with (1 + (m - n)); auto with zarith.
cut (0 <= m - n); auto with zarith; unfold Zabs_nat.
case (m - n); auto with zarith.
intros p; case p; simpl; auto with zarith.
intros p1 Hp1; rewrite nat_of_P_xO; rewrite nat_of_P_xI;
 rewrite nat_of_P_succ_morphism.
simpl; repeat rewrite plus_0_r.
repeat rewrite <- plus_n_Sm; simpl; auto.
intros p H3; contradict H3; auto with zarith.
intros H1 H2; apply iter_permutation; auto with zarith.
apply permutation_trans
     with (rev (progression Zsucc m (Zabs_nat ((1 + n) - m)))).
rewrite Zprogression_opp; auto with zarith.
replace (m + Z_of_nat (pred (Zabs_nat ((1 + n) - m)))) with n; auto.
replace (Zabs_nat ((1 + n) - m)) with (S (Zabs_nat (n - m))); auto with zarith.
simpl.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
replace ((1 + n) - m) with (1 + (n - m)); auto with zarith.
cut (0 <= n - m); auto with zarith; unfold Zabs_nat.
case (n - m); auto with zarith.
intros p; case p; simpl; auto with zarith.
intros p1 Hp1; rewrite nat_of_P_xO; rewrite nat_of_P_xI;
 rewrite nat_of_P_succ_morphism.
simpl; repeat rewrite plus_0_r.
repeat rewrite <- plus_n_Sm; simpl; auto.
intros p H3; contradict H3; auto with zarith.
apply permutation_rev.
Qed.

Lemma Zsum_split_up:
 forall (n m p : Z) (f : Z ->  Z),
 ( n <= m < p ) ->  Zsum n p f = Zsum n m f + Zsum (m + 1) p f.
intros n m p f [H H0].
case (Zle_lt_or_eq _ _ H); clear H; intros H.
unfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.
assert (H1: n < p).
apply Zlt_trans with ( 1 := H ); auto with zarith.
assert (H2: m < 1 + p).
apply Zlt_trans with ( 1 := H0 ); auto with zarith.
assert (H3: n < 1 + m).
apply Zlt_trans with ( 1 := H ); auto with zarith.
assert (H4: n < 1 + p).
apply Zlt_trans with ( 1 := H1 ); auto with zarith.
replace (Zabs_nat ((1 + p) - (m + 1)))
     with (minus (Zabs_nat ((1 + p) - n)) (Zabs_nat ((1 + m) - n))).
apply iter_progression_app; auto with zarith.
apply inj_le_rev.
(repeat rewrite inj_Zabs_nat); auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
rewrite next_n_Z; auto with zarith.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
apply inj_eq_rev; auto with zarith.
rewrite inj_minus1; auto with zarith.
(repeat rewrite inj_Zabs_nat); auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
apply inj_le_rev.
(repeat rewrite inj_Zabs_nat); auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
subst m.
rewrite Zsum_nn; auto with zarith.
unfold Zsum; generalize (Zle_cases n p); generalize (Zle_cases (n + 1) p);
 case (Zle_bool n p); case (Zle_bool (n + 1) p); auto with zarith.
intros H1 H2.
replace (Zabs_nat ((1 + p) - n)) with (S (Zabs_nat (p - n))); auto with zarith.
replace (n + 1) with (Zsucc n); auto with zarith.
replace ((1 + p) - Zsucc n) with (p - n); auto with zarith.
apply inj_eq_rev; auto with zarith.
rewrite inj_S; (repeat rewrite inj_Zabs_nat); auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
Qed.

Lemma Zsum_S_left:
 forall (n m : Z) (f : Z ->  Z), n < m ->  Zsum n m f = f n + Zsum (n + 1) m f.
intros n m f H; rewrite (Zsum_split_up n n m f); auto with zarith.
rewrite Zsum_nn; auto with zarith.
Qed.

Lemma Zsum_S_right:
 forall (n m : Z) (f : Z ->  Z),
 n <= m ->  Zsum n (m + 1) f = Zsum n m f  + f (m + 1).
intros n m f H; rewrite (Zsum_split_up n m (m + 1) f); auto with zarith.
rewrite Zsum_nn; auto with zarith.
Qed.

Lemma Zsum_split_down:
 forall (n m p : Z) (f : Z ->  Z),
 ( p < m <= n ) ->  Zsum n p f = Zsum n m f  + Zsum (m - 1) p f.
intros n m p f [H H0].
case (Zle_lt_or_eq p (m - 1)); auto with zarith; intros H1.
pattern m at 1; replace m with ((m - 1) + 1); auto with zarith.
repeat rewrite (Zsum_swap n).
rewrite (Zsum_swap (m - 1)).
rewrite Zplus_comm.
apply Zsum_split_up; auto with zarith.
subst p.
repeat rewrite (Zsum_swap n).
rewrite Zsum_nn.
unfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.
replace (Zabs_nat ((1 + n) - (m - 1))) with (S (Zabs_nat (n - (m - 1)))).
rewrite Zplus_comm.
replace (Zabs_nat ((1 + n) - m)) with (Zabs_nat (n - (m - 1))); auto with zarith.
pattern m at 4; replace m with (Zsucc (m - 1)); auto with zarith.
apply f_equal with ( f := Zabs_nat ); auto with zarith.
apply inj_eq_rev; auto with zarith.
rewrite inj_S.
(repeat rewrite inj_Zabs_nat); auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
Qed.

Lemma Zsum_ext:
 forall (n m : Z) (f g : Z ->  Z),
 n <= m ->
 (forall (x : Z), ( n <= x <= m ) ->  f x = g x) ->  Zsum n m f = Zsum n m g.
intros n m f g HH H.
unfold Zsum; auto.
unfold Zsum; (repeat rewrite Zle_imp_le_bool); auto with zarith.
apply iter_ext; auto with zarith.
intros a H1; apply H; auto; split.
apply Zprogression_le_init with ( 1 := H1 ).
cut (a < Zsucc m); auto with zarith.
replace (Zsucc m) with (n + Z_of_nat (Zabs_nat ((1 + m) - n))); auto with zarith.
apply Zprogression_le_end; auto with zarith.
rewrite inj_Zabs_nat; auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
Qed.

Lemma Zsum_add:
 forall (n m : Z) (f g : Z ->  Z),
  Zsum n m f  + Zsum n m g = Zsum n m (fun (i : Z) => f i + g i).
intros n m f g; unfold Zsum; case (Zle_bool n m); apply iter_comp;
 auto with zarith.
Qed.

Lemma Zsum_times:
 forall n m x f,  x * Zsum n m f = Zsum n m (fun i=> x * f i).
intros n m x f.
unfold Zsum. case (Zle_bool n m); intros; apply iter_comp_const with (k := (fun y : Z => x * y)); auto with zarith.
Qed.

Lemma inv_Zsum:
 forall (P : Z ->  Prop) (n m : Z) (f : Z ->  Z),
 n <= m ->
 P 0 ->
 (forall (a b : Z), P a -> P b ->  P (a + b)) ->
 (forall (x : Z), ( n <= x <= m ) ->  P (f x)) ->  P (Zsum n m f).
intros P n m f HH H H0 H1.
unfold Zsum; rewrite Zle_imp_le_bool; auto with zarith; apply iter_inv; auto.
intros x H3; apply H1; auto; split.
apply Zprogression_le_init with ( 1 := H3 ).
cut (x < Zsucc m); auto with zarith.
replace (Zsucc m) with (n + Z_of_nat (Zabs_nat ((1 + m) - n))); auto with zarith.
apply Zprogression_le_end; auto with zarith.
rewrite inj_Zabs_nat; auto with zarith.
(repeat rewrite Zabs_eq); auto with zarith.
Qed.

Lemma Zsum_pred:
 forall (n m : Z) (f : Z ->  Z),
  Zsum n m f = Zsum (n + 1) (m + 1) (fun (i : Z) => f (Zpred i)).
intros n m f.
unfold Zsum.
generalize (Zle_cases n m); generalize (Zle_cases (n + 1) (m + 1));
 case (Zle_bool n m); case (Zle_bool (n + 1) (m + 1)); auto with zarith.
replace ((1 + (m + 1)) - (n + 1)) with ((1 + m) - n); auto with zarith.
intros H1 H2; cut (exists c , c = Zabs_nat ((1 + m) - n) ).
intros [c H3]; rewrite <- H3.
generalize n; elim c; auto with zarith; clear H1 H2 H3 c n.
intros c H n; simpl; eq_tac; auto with zarith.
eq_tac; unfold Zpred; auto with zarith.
replace (Zsucc (n + 1)) with (Zsucc n + 1); auto with zarith.
exists (Zabs_nat ((1 + m) - n)); auto.
replace ((1 + (n + 1)) - (m + 1)) with ((1 + n) - m); auto with zarith.
intros H1 H2; cut (exists c , c = Zabs_nat ((1 + n) - m) ).
intros [c H3]; rewrite <- H3.
generalize n; elim c; auto with zarith; clear H1 H2 H3 c n.
intros c H n; simpl; (eq_tac; auto with zarith).
eq_tac; unfold Zpred; auto with zarith.
replace (Zpred (n + 1)) with (Zpred n + 1); auto with zarith.
unfold Zpred; auto with zarith.
exists (Zabs_nat ((1 + n) - m)); auto.
Qed.

Theorem Zsum_c:
 forall (c p q : Z), p <= q ->  Zsum p q (fun x => c) = ((1 + q) - p) * c.
intros c p q Hq; unfold Zsum.
rewrite Zle_imp_le_bool; auto with zarith.
pattern ((1 + q) - p) at 2.
 rewrite <- Zabs_eq; auto with zarith.
 rewrite <- inj_Zabs_nat; auto with zarith.
cut (exists r , r = Zabs_nat ((1 + q) - p) );
 [intros [r H1]; rewrite <- H1 | exists (Zabs_nat ((1 + q) - p))]; auto.
generalize p; elim r; auto with zarith.
intros n H p0; replace (Z_of_nat (S n)) with (Z_of_nat n + 1); auto with zarith.
simpl; rewrite H; ring.
rewrite inj_S; auto with zarith.
Qed.

Theorem Zsum_Zsum_f:
 forall (i j k l : Z) (f : Z -> Z ->  Z),
 i <= j ->
 k < l ->
  Zsum i j (fun x => Zsum k (l + 1) (fun y => f x y)) =
  Zsum i j (fun x => Zsum k l (fun y => f x y) + f x (l + 1)).
intros; apply Zsum_ext; intros; auto with zarith.
rewrite Zsum_S_right; auto with zarith.
Qed.

Theorem Zsum_com:
 forall (i j k l : Z) (f : Z -> Z ->  Z),
  Zsum i j (fun x => Zsum k l (fun y => f x y)) =
  Zsum k l (fun y => Zsum i j (fun x => f x y)).
intros; unfold Zsum; case (Zle_bool i j); case (Zle_bool k l); apply iter_com;
 auto with zarith.
Qed.

Theorem Zsum_le:
 forall (n m : Z) (f g : Z ->  Z),
 n <= m ->
 (forall (x : Z), ( n <= x <= m ) ->  (f x <= g x )) ->
  (Zsum n m f <= Zsum n m g ).
intros n m f g Hl H.
unfold Zsum; rewrite Zle_imp_le_bool; auto with zarith.
unfold Zsum;
 cut
  (forall x,
   In x (progression Zsucc n (Zabs_nat ((1 + m) - n))) ->  ( f x <= g x )).
elim (progression Zsucc n (Zabs_nat ((1 + m) - n))); simpl; auto with zarith.
intros x H1; apply H; split.
apply Zprogression_le_init with ( 1 := H1 ); auto.
cut (x < m + 1); auto with zarith.
replace (m + 1) with (n + Z_of_nat (Zabs_nat ((1 + m) - n))); auto with zarith.
apply Zprogression_le_end; auto with zarith.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
Qed.

Theorem iter_le:
forall (f g: Z -> Z)  l, (forall a, In a l -> f a <= g a) ->
  iter 0 f Zplus l <= iter 0 g Zplus l.
intros f g l; elim l; simpl; auto with zarith.
Qed.

Theorem Zsum_lt:
 forall n m f g,
 (forall x, n <= x -> x <= m ->  f x <= g x) ->
 (exists x, n <= x /\ x <= m /\  f x < g x) ->
  Zsum n m f < Zsum n m g.
intros n m f g H (d, (Hd1, (Hd2, Hd3))); unfold Zsum; rewrite Zle_imp_le_bool; auto with zarith.
cut (In d (progression  Zsucc n (Zabs_nat (1 + m - n)))).
cut (forall x, In x (progression Zsucc n (Zabs_nat (1 + m - n)))->  f x <= g x).
elim (progression  Zsucc n (Zabs_nat (1 + m - n))); simpl; auto with zarith.
intros a l Rec  H0 [H1 | H1]; subst; auto.
apply Zle_lt_trans with (f d + iter 0 g Zplus l); auto with zarith.
apply Zplus_le_compat_l.
apply iter_le; auto.
apply Zlt_le_trans with (f a + iter 0 g Zplus l); auto with zarith.
intros x H1; apply H.
apply Zprogression_le_init with ( 1 := H1 ); auto.
cut (x < m + 1); auto with zarith.
replace (m + 1) with (n + Z_of_nat (Zabs_nat ((1 + m) - n))); auto with zarith.
apply Zprogression_le_end with ( 1 := H1 ); auto with arith.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
apply in_Zprogression.
rewrite inj_Zabs_nat; auto with zarith.
rewrite Zabs_eq; auto with zarith.
Qed.

Theorem Zsum_minus:
 forall n m f g,  Zsum n m f - Zsum n m g = Zsum n m (fun x => f x - g x).
intros n m f g; apply trans_equal with (Zsum n m f + (-1) * Zsum n m g); auto with zarith.
rewrite Zsum_times; rewrite Zsum_add; auto with zarith.
Qed.


(********** Denotational semantics preserves types  **********)
(**********    (and is total on typed contracts)    **********)

Require Import Equality.
Require Import Denotational.

(* Typing of values *)

Reserved Notation "'|-V' e '∶' t" (at level 20).

Inductive TypeVal : Val -> Ty -> Prop :=
| type_bool b : |-V BVal b ∶ BOOL
| type_real b : |-V RVal b ∶ REAL
        where "'|-V' v '∶' t" := (TypeVal v t).

(* Typing of partial values *)

Reserved Notation "'|-V'' e '∶' t" (at level 20).

Inductive TypeVal' : option Val -> Ty -> Prop :=
| type_some v t : |-V v ∶ t -> |-V' Some v ∶ t
| type_none t : |-V' None ∶ t
        where "'|-V'' v '∶' t" := (TypeVal' v t).

Hint Constructors TypeVal TypeVal'.

(* Typing of external environments *)

Definition TypeExt (ext : ExtEnv) := forall z l t, |-O l ∶ t -> |-V (ext l z)  ∶ t.

Lemma adv_ext_type e d : TypeExt e -> TypeExt (adv_ext d e).
Proof.
  unfold TypeExt, adv_ext. intros. auto.
Qed.

Hint Resolve adv_ext_type.

(* Typing of environments *)

Definition TypeEnv (g : TyEnv) (env : Env) : Prop := all2 TypeVal env g.

Hint Unfold TypeEnv.

(* Typing of arguments (to an operation). *)

Definition TypeArgs (ts : list Ty) (args : list Val) : Prop := all2 TypeVal args ts.

Lemma OpSem_typed_total {A} op ts t (args : list A) (f : A -> option Val) :
|-Op op ∶ ts => t -> all2 (fun x t => exists v, f x = Some v /\ |-V v ∶ t) args ts ->
                     exists v, (mapM f args >>= OpSem op) = Some v /\ |-V v ∶ t.
Proof.
  intros O T. induction O;
  repeat (match goal with
      | [ H : exists _, _ /\ _ |- _ ] =>
        let H1 := fresh in let H2 := fresh in let H3 := fresh in
        let H4 := fresh in
        destruct H as [H1 H2]; destruct H2 as [H3 H4]; rewrite H3 in *; inversion H4
      | [H : all2 _ _ _ |- _] => inversion H; clear H
  end; subst; simpl; unfold liftM2, bind); eexists; auto.
Qed.

(* The denotational semantics of expressions is total and produces
values of the correct type. *)

Theorem Esem_typed_total g e t (env : Env) (ext : ExtEnv) :
  g |-E e ∶ t -> TypeEnv g env -> TypeExt ext -> (exists v, E[|e|] env ext = Some v /\ |-V v ∶ t).
Proof.
  intros E R V'. generalize dependent env. generalize dependent ext.
  dependent induction E using TypeExp_ind'; intros.
  + simpl. rewrite sequence_map. eapply OpSem_typed_total. apply H.
    do 4 (eapply all2_apply in H1;eauto).
  + simpl. eauto.
  + simpl. generalize dependent env.
    generalize dependent g. induction v; intros.
    - inversion H. subst. inversion R. subst. simpl. eauto.
    - simpl. inversion H. subst. inversion R. subst. eapply IHv.
      apply H2. auto.
  + simpl. eapply Acc_sem_ind. intros. decompose [ex and] H. subst.
    simpl. apply IHE1; auto. apply IHE2; auto.
Qed.

Corollary Esem_typed g e t (env : Env) (ext : ExtEnv) v :
  g |-E e ∶ t -> TypeEnv g env -> TypeExt ext ->  E[|e|] env ext = Some v -> |-V v ∶ t.
Proof.
  intros T T1 T2 S. eapply Esem_typed_total in T; eauto. decompose [ex and] T.
  rewrite H0 in S. inversion S. subst. assumption.
Qed.

Definition total_trace (t : option Trace) := exists v, t = Some v.

Hint Unfold empty_trace empty_trans const_trace empty_trans
     total_trace singleton_trace singleton_trans scale_trace scale_trans.

(* The denotational semantics of contracts is total. *)

Theorem Csem_typed_total c g (env: Env) (ext : ExtEnv) :
 g |-C c -> TypeEnv g env -> TypeExt ext -> total_trace (C[|c|] env ext).
Proof.
  intros C T R. generalize dependent env. generalize dependent ext. generalize dependent g.
  unfold total_trace. induction c.
  + simpl. repeat autounfold. eauto.
  + simpl. repeat autounfold. intros. inversion C; subst. clear C.
    eapply Esem_typed_total in H2; eauto. decompose [ex and] H2. rewrite H0.
    assert (TypeEnv (t :: g) (x :: env)) as T'. constructor; auto.
    destruct (IHc (t :: g) H3 ext R (x :: env) T'). simpl. rewrite H. eauto.
  + simpl. repeat autounfold. intros. eauto.
  + simpl. repeat autounfold. intros. unfold liftM2, bind.
    inversion C. subst. destruct (IHc g H3 ext R env T).
    eapply Esem_typed_total in H2; eauto. decompose [and ex] H2.
    rewrite H1. inversion H4. simpl. rewrite  H.
    unfold pure, compose. eauto.
  + intros. simpl. unfold delay_trace. inversion C; subst.
    assert (TypeExt (adv_ext (Z.of_nat n) ext)) as R' by auto.
    destruct (IHc g H1 (adv_ext (Z.of_nat n) ext) R' env T).
    rewrite H. simpl. autounfold; eauto.
  + intros. simpl. unfold add_trace, add_trans, liftM2, bind. inversion C; subst.
    destruct (IHc1 g H2 ext R env T). rewrite H.
    destruct (IHc2 g H3 ext R env T). rewrite H0.
    unfold pure, compose. eauto.
  + simpl. induction n; intros;inversion C; subst.
    - simpl. eapply  Esem_typed_total in H3; eauto. decompose [and ex] H3.
      rewrite H0. inversion H1. destruct b; eauto.
    - simpl. eapply  Esem_typed_total in H3; eauto. decompose [and ex] H3.
      rewrite H0. inversion H1. destruct b; eauto.
      assert (TypeExt (adv_ext 1 ext)) as R' by auto.
      assert (g |-C If e n c1 c2) as C' by (inversion C; constructor;auto).
      destruct (IHn g C' (adv_ext 1 ext) R' env T).
      rewrite H2. simpl. autounfold. eauto.
Qed.


Require Export Iron.Language.SystemF2Data.Exp.Base.
Require Export Iron.Language.SystemF2Data.Exp.Relation.WfX.

(********************************************************************)
(* Weak normal forms cannot be reduced further by
   call-by-value evaluation. *)
Inductive wnfX : exp -> Prop :=
 | Wnf_XVar
   : forall i
   , wnfX (XVar i)

 | Wnf_XLAM
   : forall x1
   , wnfX (XLAM x1)

 | Wnf_XLam
   : forall t1 x2
   , wnfX (XLam t1 x2)

 | Wnf_XCon
   :  forall dc ts xs
   ,  Forall wnfX xs
   -> wnfX (XCon dc ts xs)

 | Wnf_XLit
   :  forall l
   ,  wnfX (XLit l).
Hint Constructors wnfX.

(********************************************************************)
(* Values are closed expressions that cannot be reduced further. *)
Inductive value : exp -> Prop :=
 | Value
   :  forall xx
   ,  wnfX xx -> closedX xx
   -> value xx.
Hint Constructors value.

Lemma value_wnfX
 : forall xx, value xx -> wnfX xx.
 Proof. intros. inverts H. auto. Qed.
Hint Resolve value_wnfX.

Lemma value_closedX
 : forall xx, value xx -> closedX xx.
 Proof. intros. inverts H. auto. Qed.
Hint Resolve value_closedX.

Lemma value_wnfXs_XCon
 : forall ts xs dc
 , value (XCon dc ts xs) -> Forall wnfX xs.
Proof.
 intros. inverts H. inverts H0. auto.
Qed.
Hint Resolve value_wnfXs_XCon.

Lemma value_closedXs_XCon
 : forall ts xs dc
 , value (XCon dc ts xs) -> Forall closedX xs.
Proof.
 intros. inverts H. inverts H1. auto.
Qed.
Hint Resolve value_closedXs_XCon.


From Ltac2 Require Import Ltac2.

(* Simple expressions *)
(* Note that int is not a data type available in Gallina *)
(* It is primitive data type in Ltac2 *)
Ltac2 Eval 1.

Ltac2 Eval Int.add 1 2.

(* Lambdas *)
Ltac2 Eval (fun x => x).

(* See https://github.com/coq/coq/blob/master/user-contrib/Ltac2/ for
   the Ltac2 standard library functions *)
Ltac2 Eval (fun x => Int.add x x) 4.

(* Let bindings *)
Ltac2 Eval let f := fun x => Int.add x x in f 4.

(* Top-level functions *)
Ltac2 double_int := fun x => Int.add x x.

(* A syntax sugar of the former *)
Ltac2 double_int' x := Int.add x x.

(* We can add annotations to our types *)
Ltac2 double_int'' (x : int) := Int.add x x.

Ltac2 Eval double_int 4.

Ltac2 is_even x := Int.equal (Int.mod x 2) 0.

(* Recursive functions *)
Ltac2 rec collatz n :=
  if Int.le n 1
  then 0
  else
    (* if is_even x *)
    if is_even n
    then Int.add 1 (collatz (Int.div n 2))
    else Int.add 1 (collatz (Int.add 1 (Int.mul 3 n))).

Ltac2 Eval collatz 10.

(* Algebraic data types *)
Ltac2 Type rec PNat :=
  [ Z | S (PNat) ].

Ltac2 rec padd (m : PNat) (n : PNat) :=
  match m with
  | Z => n
  | S m => S (padd m n)
  end.

Ltac2 Eval padd (S (S Z)) (S Z).

(* Type parameters *)
Ltac2 Type rec 'a Tree :=
  [ Empty | Node ('a, 'a Tree, 'a Tree)].

Ltac2 rec tree_size (t : 'a Tree) :=
  match t with
  | Empty => 0
  | Node _ l r => Int.add 1 (Int.add (tree_size l) (tree_size r))
  end.

Ltac2 Eval tree_size (Node 1 (Node 2 Empty Empty) Empty).

(* Records *)
Ltac2 Type ('a, 'b) Pair := { fst : 'a ; snd : 'b }.

Ltac2 Eval { fst := 1 ; snd := 2 }.

(* Projecting out a record *)
Ltac2 Eval { fst := 1 ; snd := "2" }.(fst).

Ltac2 Eval let p := { fst := 1 ; snd := "2" } in p.(snd).

(* Constructing Gallina terms *)
(* To construct a Gallina term, we want to quote it with ' *)
Ltac2 Eval '1.
(* constr is a type that represents a Gallina term *)

Ltac2 Eval '(1 + 1).

(* Of course, we can refer to Gallina top-level definitions *)
Definition four := 4.

Ltac2 Eval 'four.

(* Ltac2 Eval four. *)

(* Ltac2 Eval 'five. *)

(* int_n 3 ~> (1 + (1 + (1 + 0))) *)
(* int_n 0 ~> 0 *)

(* Inside a quote, we can refer to Ltac2 variables using $ *)
(* If you are familiar with lisp, think of ' as `
   $ as , that only works with variables *)
Ltac2 rec int_n n :=
  if Int.le n 0
  then '0
  else let m := int_n (Int.sub n 1) in
       '(1 + $m).

Ltac2 Eval int_n 4.

(* We can use Constr.equal to test the syntactic equality (up to
   alpha-equivalence) of Gallina terms *)
Ltac2 Eval Constr.equal '(fun x : nat => x) '(fun z : nat => z).

(* Ltac2 is impure. Apart from mutable cells, it's possible to query
and mutate the proof state *)

(* First, let's see how we can query the proof state *)

(* The built-in function hyps give us a list of hypotheses in the
   proof context. We can use it to build a tactic that works like
   assumption *)
Ltac2 Eval Control.hyps.
(* Control.hyps : unit -> (ident * constr option * constr) list *)
(* Return the hypotheses as a list of (hyp-name, definition, type).
   list is a data structure defined in the Ltac2 standard library.
   You can find its related utility functions in the Ltac2.List module *)
(* Control.hyps needs to be a function because Ltac2 is a
   call-by-value language and a variable of type ... list would be a
   constant *)

(* The built-in function goal returns a gallina term that represents
   the goal *)
Ltac2 Eval Control.goal.
(* Control.goal : unit -> constr = <fun> *)

Lemma ex1 : 1 = 2 -> 1 = 2.
Proof.
  intro H.
  pose 4.

  Ltac2 Eval Control.hyps ().
  (* (@H, None, constr:(1 = 2)); *)
  (* (@n, Some (constr:(4)), constr:(nat)) *)

  Ltac2 Eval Control.goal ().
  (* constr:(1 = 2) *)

  (* We can use the List.find from the standard library to look for an
     element from the list that we are interested in *)
  Ltac2 Eval List.find (fun (_,_,ty) => Constr.equal ty 'nat) (Control.hyps ()).
  (* (@n, Some (constr:(4)), constr:(nat)) *)
Abort.

(* find_assumption finds a hypothesis that matches the goal *)
(* In general, Ltac2 foo () := ... defines a function that takes
   a unit as its first argument *)
Ltac2 find_assumption () : constr :=
  let g := Control.goal () in
  let h := List.find (fun (_,_,ty) => Constr.equal g ty) (Control.hyps ()) in
  match h with
  (* h_ident is an identifier. We need to use Control.hyp to turn it
     into a Gallina term *)
  | (h_ident, _, _) => Control.hyp h_ident
  end.

Lemma ex2 : 1 = 2 -> 1 = 2.
Proof.
  intro H.
  Ltac2 Eval find_assumption ().

  (* find_assumption () will find H as the hypothesis matching our goal *)
  (* So far, we have only queried the proof state, but we haven't
     really changed it *)
  (* One way to change the proof state is to simply finish the proof *)
  (* Control.refine takes a computation that returns a Gallina term
     and use that Gallina term to complete the goal. Control.refine
     returns unit because its meant to mutate the proof state. *)
  Control.refine find_assumption.
  (* Now the goal is completed *)
Qed.

(* We can now implement our own assumption tactic as follows: *)
Ltac2 my_assumption () :=
  Control.refine find_assumption.

Lemma id_prop (A : Prop) : A -> A.
Proof.
  intro H.
  my_assumption ().
Qed.

(* Our tactic looks odd since we always need to explicitly add ()
   after it. *)
(* To use your Ltac2 tactic in your proof script, you want to create a
   notation for it so you don't have to type in the () each time *)

(* Note that it is not a cyclic definition. The my_assumption on the
   RHS of := is bound to the Ltac2 definition from earlier. *)
Ltac2 Notation "my_assumption" := my_assumption ().

Lemma id_prop' (A : Prop) : A -> A.
Proof.
  intro H.
  my_assumption.
Qed.

(* In fact, the moment you require and import Ltac2 in your coq file,
   all the tactics in your proof script will refer to Ltac2
   tactics/notations by default, including intro and pose we used
   earlier *)
(* https://github.com/coq/coq/blob/master/user-contrib/Ltac2/Notations.v *)
(* The Ltac2 standard library is far from complete. Many tactics
   available in Ltac1 are missing *)
Goal forall P Q, (P -> Q) -> P -> Q.
  Fail tauto.
Abort.

(* We can make foreign call to Ltac1 libraries through ltac1:(..) *)
(* We can reuse the name tauto because Ltac1 and Ltac2 don't share the
   same namespace *)
Ltac2 tauto () := ltac1:(tauto).
(* tauto on the RHS of := refers to the tauto defined in Ltac1 *)
(* Again, it makes no sense to write tauto as a variable of type unit
   in a call-by-value language. We need to define it as a function so
   it can perform some action *)
(* To get rid of the parentheses, we use the same notation trick *)
Ltac2 Notation "tauto" := tauto ().

Goal forall P Q, (P -> Q) -> P -> Q.
  tauto.
Qed.

(* Tactics that take arguments are trickier because if we don't even
   have the type information of how many arguments the Ltac1 tactic
   takes *)

(* Let's write an Ltac2 wrapper for the pick fresh tactic from the metalib *)
Require Import Metalib.Metatheory.

Ltac2 pick_fresh_for (x : ident) (l : constr) :=
  ltac1:( x l |- pick fresh x for l) (Ltac1.of_ident x) (Ltac1.of_constr l).
(* ltac1:(a b |- ...) has the signature Ltac1.t -> Ltac1.t -> unit *)
(* Ltac1.t is an opaque type that represents an untyped Ltac1 argument *)
Ltac2 Eval Ltac1.of_ident.

(* Since pick_fresh_for takes two arguments, we want to use a fancier
   notation *)
Ltac2 Notation "pick" "fresh" x(ident) "for" l(constr) :=
  pick_fresh_for x l.

(* Note that if we declare an notation argument as a constr, then
   whatever we pass in to the notation at that position is implicitly
   quoted. *)
(* TODO: example *)

(* Extra: More on constr  *)
(* constr is an opaque type so we can't directly pattern match on it
   as if it is an algebraic data type. Instead, we must use special
   match! and lazy_match! forms *)

Ltac2 rec mirror_plus (tm : constr) :=
  lazy_match! tm with
  | ?a + ?b =>
      let rev_b := mirror_plus b in
      let rev_a := mirror_plus a in
      '($rev_b + $rev_a)
      (* rev_b and rev_a are Ltac2 variables representing Gallina terms *)
      (* We need to use antiquote to refer to these metavariables
         within a Gallina term *)
  | _ => tm
  end.

Ltac2 Eval mirror_plus '(1 + 2 + 3).

(* Just like in Ltac1, we can also match the entire proof context.
   As an example, we define an alternative version of my_assumption *)
Ltac2 my_assumption' () :=
  (* goal is not a variable. lazy_match! goal with is its own syntactic form *)
  lazy_match! goal with
  (* match! goal with would also work *)
  | [ h_ident : ?a |- ?a ] =>
      (* Again, h_ident is of type identifier. We need to use
         Control.hyp to perform a lookup in the proof context and
         produce a Gallina term *)
      let h := Control.hyp h_ident in
      Control.refine (fun _ => h)
  end.

Goal forall A, A -> A.
Proof.
  intros.
  my_assumption' ().
Qed.

(* However, my_assumption' doesn't work as expected when we put it
   behind a semicolon to discharge multiple goals *)
Goal forall A, A \/ A -> A.
Proof.
  Fail (intros A [? | ?]; my_assumption' ()).
  (* The reason is that Ltac2 doesn't always focus on the individual
     goals automatically when multiple goals are produced by the
     previous tactic. We need to use Control.enter to explicitly focus
     on each individaul goals *)
  Ltac2 Eval Control.enter.

  intros A [? | ?]; Control.enter my_assumption'.
Qed.

(* We can now wrap my_assumption' inside a notation *)
Ltac2 Notation "my_assumption'" := Control.enter my_assumption'.

Goal forall A, A \/ A -> A.
Proof.
  intros A [? | ?]; my_assumption'.
Qed.

(* Bonus: Unsafe.kind: traverse the Gallina AST explicitly *)
(* Constr.Unsafe.kind turns a constr into an exported algebraic data type
   kind that you can match against. However, it is unsafe because you can
   easily end up with open terms... *)


(**************************************************************)
(*   Copyright Dominique Larchey-Wendling [*]                 *)
(*                                                            *)
(*                             [*] Affiliation LORIA -- CNRS  *)
(**************************************************************)
(*      This file is distributed under the terms of the       *)
(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)
(**************************************************************)

(** Extraction of breadth-first numbering algorithm from Coq to Ocaml

       see http://okasaki.blogspot.com/2008/07/breadth-first-numbering-algorithm-in.html
       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/jfp95queue.pdf
       and https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf
       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/icfp00bfn.pdf

*)

(* Experimental STUFF that DOES NOT WORK *)

Require Import List Arith Omega Wellfounded.
Require Import list_utils wf_utils bt bft fifo.

Set Implicit Arguments.

Section seq_an.

  (* seq_an a n = [a;a+1;...;a+(n-1)] *)

  Fixpoint seq_an a n : list nat :=
    match n with
      | 0    => nil
      | S n  => a::seq_an (S a) n
    end.

  Fact seq_an_length a n : length (seq_an a n) = n.
  Proof. revert a; induction n; simpl; intros; f_equal; auto. Qed.

  Fact seq_an_spec a n x : In x (seq_an a n) <-> a <= x < a+n.
  Proof.
    revert x a; induction n as [ | n IHn ]; intros x a; simpl;
      [ | rewrite IHn ]; omega.
  Qed.

End seq_an.

Section streams.

  Variable X : Type.

  CoInductive stream := in_stream : X -> stream -> stream.

  Fixpoint take n s :=
    match n with
      | 0   => nil
      | S n => match s with in_stream x s => x::take n s end
    end.

  Fixpoint leave n s :=
    match n with
      | 0   => s
      | S n => match s with in_stream _ s => leave n s end
    end.

  Definition shead s := match s with in_stream x _ => x end.
  Definition stail s := match s with in_stream _ s => s end.

  Fixpoint prefix l s :=
    match l with
      | nil  => True
      | x::l => match s with in_stream y s => x = y /\ prefix l s end
    end.

End streams.

CoInductive lbt X :=
  | lleaf : X -> lbt X
  | lnode : lbt X -> X -> lbt X -> lbt X.

Section bfn_stream.

  Variable X : Type.

  Implicit Type (t : bt X) (s : stream nat).

  CoFixpoint cst (x : X) := in_stream x (cst x).

  CoFixpoint  bfn2 t s :=
    match s with
      | in_stream k s =>
      match t with
        | leaf _     => in_stream (S k) s
        | node a _ b => let s'  := bfn2 a s in
                        let s'' := bfn2 b s'
                        in  in_stream (S k) s''
      end
    end.

  CoFixpoint bfn1 t s :=
     match s with
      | in_stream k s =>
      match t with
        | lleaf x     => lleaf k
        | lnode a x b => let (a',s')  := (bfn1 a s, bfn2 a s) in
                         let (b',s'') := (bfn1 b s', bfn2 b s')
                         in  lnode a' k b'
      end
    end
  with bfn2 t s :=
    match s with
      | in_stream k s =>
      match t with
        | lleaf x     => in_stream (S k) s
        | lnode a x b => let s'  := bfn2 a s in
                         let s'' := bfn2 b s'
                         in  in_stream (S k) s''
      end
    end.
.

  Fixpoint bfn t s { struct t } : bt nat * stream nat :=
    match s with
      | in_stream k s =>
      match t with
        | leaf x     => (leaf k, in_stream (S k) s)
        | node a x b => let (a',s')  := bfn a s  in
                        let (b',s'') := bfn b s'
                        in  (node a' k b',in_stream (S k) s'')
      end
    end.

  Definition sfst s := match s with in_stream x _ => x end.
  Definition ssnd s := match s with in_stream _ s => s end.

  (* I should be able to write this but Coq does not type-check the
     nested co-recursive call *)

  Fixpoint bfn_2 t s : stream nat := in_stream (S (sfst s)) (match t with
        | leaf _     => s
        | node a _ b => bfn_2 b (bfn_2 a s)
      end).

  CoFixpoint s t := bfn_2 t (in_stream 1 (s t)).

  Section test.

    Variable t : bt X.

  Definition label t :=
    cofix s := snd (bfn t (in_stream 1 s)).
    let (t',s) := bfn t (in_stream 1 s) in t'.
        prefix (first_available (shead s) t) s
    ->  { c :

  Variable P : bt X -> stream nat -> stream nat -> Prop.

  Fixpoint cumul k l :=
    match l with
      | nil  => nil
      | x::l => k::cumul (x+k) l
    end.

  Definition first_available k t := cumul k (map (@length _) (niveaux_tree t)).

  Fixpoint bfn_stream t s { struct t } :
        prefix (first_available (shead s) t) s
    ->  { c : bt nat * stream nat |
          let (t',s') := c in t ~t t' /\ s' = stail s }.
  Proof.
    intros H.
    destruct s as [ k s ]; simpl in *.
    destruct t as [ x | a x b ]; simpl in *.
    + exists (leaf k, in_stream (S k) s); simpl.
      split; auto.
      split.
      * unfold bft.
        rewrite bft_f_fix_3; simpl.
        rewrite bft_f_fix_0; auto.
      * admit.
    + destruct (bfn_stream a s) as ( (a',s') & H1 & H2 & H3).
      destruct (bfn_stream b s') as ( (b',s'') & H4 & H5 & H6).
      exists (node a' k b', in_stream (S k) s'').
      split; auto.
      split.
      * unfold bft.
        rewrite bft_f_fix_3; simpl.
        f_equal.
        rewrite bft_f_fix_3; simpl.
simpl.


(* Copyright (c) 2008-2012, 2015, Adam Chlipala
 *
 * This work is licensed under a
 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
 * Unported License.
 * The license text is available at:
 *   http://creativecommons.org/licenses/by-nc-nd/3.0/
 *)

(* begin hide *)
Require Import List.

Require Import Cpdt.CpdtTactics.

Set Implicit Arguments.
Set Asymmetric Patterns.
(* end hide *)

(** printing <-- $\longleftarrow$ *)

(** %\part{Programming with Dependent Types}

\chapter{Subset Types and Variations}% *)

(** So far, we have seen many examples of what we might call "classical program verification."  We write programs, write their specifications, and then prove that the programs satisfy their specifications.  The programs that we have written in Coq have been normal functional programs that we could just as well have written in Haskell or ML.  In this chapter, we start investigating uses of%\index{dependent types}% _dependent types_ to integrate programming, specification, and proving into a single phase.  The techniques we will learn make it possible to reduce the cost of program verification dramatically. *)

(** * Introducing Subset Types *)

(** Let us consider several ways of implementing the natural number predecessor function.  We start by displaying the definition from the standard library: *)

Print pred.
(** %\vspace{-.15in}% [[
pred = fun n : nat => match n with
                      | 0 => 0
                      | S u => u
                      end
     : nat -> nat

]]

We can use a new command, %\index{Vernacular commands!Extraction}\index{program extraction}\index{extraction|see{program extraction}}%[Extraction], to produce an %\index{OCaml}%OCaml version of this function. *)

Extraction pred.

(** %\begin{verbatim}
(** val pred : nat -> nat **)

let pred = function
  | O -> O
  | S u -> u
\end{verbatim}%

#

(** val pred : nat -> nat **)

let pred = function
  | O -> O
  | S u -> u

# *)

(** Returning 0 as the predecessor of 0 can come across as somewhat of a hack.  In some situations, we might like to be sure that we never try to take the predecessor of 0.  We can enforce this by giving [pred] a stronger, dependent type. *)

Lemma zgtz : 0 > 0 -> False.
  crush.
Qed.

Definition pred_strong1 (n : nat) : n > 0 -> nat :=
  match n with
    | O => fun pf : 0 > 0 => match zgtz pf with end
    | S n' => fun _ => n'
  end.

(** We expand the type of [pred] to include a _proof_ that its argument [n] is greater than 0.  When [n] is 0, we use the proof to derive a contradiction, which we can use to build a value of any type via a vacuous pattern match.  When [n] is a successor, we have no need for the proof and just return the answer.  The proof argument can be said to have a _dependent_ type, because its type depends on the _value_ of the argument [n].

   Coq's [Eval] command can execute particular invocations of [pred_strong1] just as easily as it can execute more traditional functional programs.  Note that Coq has decided that argument [n] of [pred_strong1] can be made _implicit_, since it can be deduced from the type of the second argument, so we need not write [n] in function calls. *)

Theorem two_gt0 : 2 > 0.
  crush.
Qed.

Eval compute in pred_strong1 two_gt0.
(** %\vspace{-.15in}% [[
     = 1
     : nat
 ]]

One aspect in particular of the definition of [pred_strong1] may be surprising.  We took advantage of [Definition]'s syntactic sugar for defining function arguments in the case of [n], but we bound the proofs later with explicit [fun] expressions.  Let us see what happens if we write this function in the way that at first seems most natural.

%\vspace{-.15in}%[[
Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=
  match n with
    | O => match zgtz pf with end
    | S n' => n'
  end.
]]

<<
Error: In environment
n : nat
pf : n > 0
The term "pf" has type "n > 0" while it is expected to have type
"0 > 0"
>>

The term [zgtz pf] fails to type-check.  Somehow the type checker has failed to take into account information that follows from which [match] branch that term appears in.  The problem is that, by default, [match] does not let us use such implied information.  To get refined typing, we must always rely on [match] annotations, either written explicitly or inferred.

In this case, we must use a [return] annotation to declare the relationship between the _value_ of the [match] discriminee and the _type_ of the result.  There is no annotation that lets us declare a relationship between the discriminee and the type of a variable that is already in scope; hence, we delay the binding of [pf], so that we can use the [return] annotation to express the needed relationship.

We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in the definition of [pred_strong1], leading to the following elaborated code: *)

Definition pred_strong1' (n : nat) : n > 0 -> nat :=
  match n return n > 0 -> nat with
    | O => fun pf : 0 > 0 => match zgtz pf with end
    | S n' => fun _ => n'
  end.

(** By making explicit the functional relationship between value [n] and the result type of the [match], we guide Coq toward proper type checking.  The clause for this example follows by simple copying of the original annotation on the definition.  In general, however, the [match] annotation inference problem is undecidable.  The known undecidable problem of%\index{higher-order unification}% _higher-order unification_ %\cite{HOU}% reduces to the [match] type inference problem.  Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations.

Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)

Extraction pred_strong1.

(** %\begin{verbatim}
(** val pred_strong1 : nat -> nat **)

let pred_strong1 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'
\end{verbatim}%

#

(** val pred_strong1 : nat -> nat **)

let pred_strong1 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'

# *)

(** The proof argument has disappeared!  We get exactly the OCaml code we would have written manually.  This is our first demonstration of the main technically interesting feature of Coq program extraction: proofs are erased systematically.

%\medskip%

We can reimplement our dependently typed [pred] based on%\index{subset types}% _subset types_, defined in the standard library with the type family %\index{Gallina terms!sig}%[sig]. *)

(* begin hide *)
(* begin thide *)
Definition bar := ex.
(* end thide *)
(* end hide *)

Print sig.
(** %\vspace{-.15in}% [[
Inductive sig (A : Type) (P : A -> Prop) : Type :=
    exist : forall x : A, P x -> sig P
]]

The family [sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop].  That means that [sig] values can survive extraction, while [ex] proofs will always be erased.  The actual details of extraction of [sig]s are more subtle, as we will see shortly.

We rewrite [pred_strong1], using some syntactic sugar for subset types. *)

Locate "{ _ : _ | _ }".
(** %\vspace{-.15in}% [[
  Notation
  "{ x : A  |  P }" := sig (fun x : A => P)
   ]]
 *)

Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
  match s with
    | exist O pf => match zgtz pf with end
    | exist (S n') _ => n'
  end.

(** To build a value of a subset type, we use the [exist] constructor, and the details of how to do that follow from the output of our earlier [Print sig] command, where we elided the extra information that parameter [A] is implicit.  We need an extra [_] here and not in the definition of [pred_strong2] because _parameters_ of inductive types (like the predicate [P] for [sig]) are not mentioned in pattern matching, but _are_ mentioned in construction of terms (if they are not marked as implicit arguments). *)

Eval compute in pred_strong2 (exist _ 2 two_gt0).
(** %\vspace{-.15in}% [[
     = 1
     : nat
     ]]
     *)

Extraction pred_strong2.

(** %\begin{verbatim}
(** val pred_strong2 : nat -> nat **)

let pred_strong2 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'
\end{verbatim}%

#

(** val pred_strong2 : nat -> nat **)

let pred_strong2 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'

#

We arrive at the same OCaml code as was extracted from [pred_strong1], which may seem surprising at first.  The reason is that a value of [sig] is a pair of two pieces, a value and a proof about it.  Extraction erases the proof, which reduces the constructor [exist] of [sig] to taking just a single argument.  An optimization eliminates uses of datatypes with single constructors taking single arguments, and we arrive back where we started.

We can continue on in the process of refining [pred]'s type.  Let us change its result type to capture that the output is really the predecessor of the input. *)

Definition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=
  match s return {m : nat | proj1_sig s = S m} with
    | exist 0 pf => match zgtz pf with end
    | exist (S n') pf => exist _ n' (eq_refl _)
  end.

(* begin hide *)
(* begin thide *)
Definition ugh := lt.
(* end thide *)
(* end hide *)

Eval compute in pred_strong3 (exist _ 2 two_gt0).
(** %\vspace{-.15in}% [[
     = exist (fun m : nat => 2 = S m) 1 (eq_refl 2)
     : {m : nat | proj1_sig (exist (lt 0) 2 two_gt0) = S m}
      ]]
     *)

(* begin hide *)
(* begin thide *)
Definition pred_strong := 0.
(* end thide *)
(* end hide *)

(** A value in a subset type can be thought of as a%\index{dependent pair}% _dependent pair_ (or%\index{sigma type}% _sigma type_) of a base value and a proof about it.  The function %\index{Gallina terms!proj1\_sig}%[proj1_sig] extracts the first component of the pair.  It turns out that we need to include an explicit [return] clause here, since Coq's heuristics are not smart enough to propagate the result type that we wrote earlier.

By now, the reader is probably ready to believe that the new [pred_strong] leads to the same OCaml code as we have seen several times so far, and Coq does not disappoint. *)

Extraction pred_strong3.

(** %\begin{verbatim}
(** val pred_strong3 : nat -> nat **)

let pred_strong3 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'
\end{verbatim}%

#

(** val pred_strong3 : nat -> nat **)

let pred_strong3 = function
  | O -> assert false (* absurd case *)
  | S n' -> n'

#

We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred].  Any other implementation of the same type must have the same input-output behavior.  However, there is still room for improvement in making this kind of code easier to write.  Here is a version that takes advantage of tactic-based theorem proving.  We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code.  (Recall that [False_rec] is the [Set]-level induction principle for [False], which can be used to produce a value in any [Set] given a proof of [False].) *)

Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.
  refine (fun n =>
    match n with
      | O => fun _ => False_rec _ _
      | S n' => fun _ => exist _ n' _
    end).

(* begin thide *)
  (** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given.  Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal.  It may seem strange to change perspective so implicitly between programming and proving, but recall that programs and proofs are two sides of the same coin in Coq, thanks to the Curry-Howard correspondence.

     We do most of the work with the %\index{tactics!refine}%[refine] tactic, to which we pass a partial "proof" of the type we are trying to prove.  There may be some pieces left to fill in, indicated by underscores.  Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal.  In this case, we have two subgoals:

[[
2 subgoals

  n : nat
  _ : 0 > 0
  ============================
   False

subgoal 2 is

 S n' = S n'
 ]]

We can see that the first subgoal comes from the second underscore passed to [False_rec], and the second subgoal comes from the second underscore passed to [exist].  In the first case, we see that, though we bound the proof variable with an underscore, it is still available in our proof context.  It is hard to refer to underscore-named variables in manual proofs, but automation makes short work of them.  Both subgoals are easy to discharge that way, so let us back up and ask to prove all subgoals automatically. *)

  Undo.
  refine (fun n =>
    match n with
      | O => fun _ => False_rec _ _
      | S n' => fun _ => exist _ n' _
    end); crush.
(* end thide *)
Defined.

(** We end the "proof" with %\index{Vernacular commands!Defined}%[Defined] instead of [Qed], so that the definition we constructed remains visible.  This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward.  (More formally, [Defined] marks an identifier as%\index{transparent}% _transparent_, allowing it to be unfolded; while [Qed] marks an identifier as%\index{opaque}% _opaque_, preventing unfolding.)  Let us see what our proof script constructed. *)

Print pred_strong4.
(** %\vspace{-.15in}% [[
pred_strong4 =
fun n : nat =>
match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
| 0 =>
    fun _ : 0 > 0 =>
    False_rec {m : nat | 0 = S m}
      (Bool.diff_false_true
         (Bool.absurd_eq_true false
            (Bool.diff_false_true
               (Bool.absurd_eq_true false (pred_strong4_subproof n _)))))
| S n' =>
    fun _ : S n' > 0 =>
    exist (fun m : nat => S n' = S m) n' (eq_refl (S n'))
end
     : forall n : nat, n > 0 -> {m : nat | n = S m}
]]

We see the code we entered, with some proofs filled in.  The first proof obligation, the second argument to [False_rec], is filled in with a nasty-looking proof term that we can be glad we did not enter by hand.  The second proof obligation is a simple reflexivity proof. *)

Eval compute in pred_strong4 two_gt0.
(** %\vspace{-.15in}% [[
     = exist (fun m : nat => 2 = S m) 1 (eq_refl 2)
     : {m : nat | 2 = S m}
     ]]

  A tactic modifier called %\index{tactics!abstract}%[abstract] can be helpful for producing shorter terms, by automatically abstracting subgoals into named lemmas. *)

(* begin thide *)
Definition pred_strong4' : forall n : nat, n > 0 -> {m : nat | n = S m}.
  refine (fun n =>
    match n with
      | O => fun _ => False_rec _ _
      | S n' => fun _ => exist _ n' _
    end); abstract crush.
Defined.

Print pred_strong4'.
(* end thide *)

(** %\vspace{-.15in}% [[
pred_strong4' =
fun n : nat =>
match n as n0 return (n0 > 0 -> {m : nat | n0 = S m}) with
| 0 =>
    fun _H : 0 > 0 =>
    False_rec {m : nat | 0 = S m} (pred_strong4'_subproof n _H)
| S n' =>
    fun _H : S n' > 0 =>
    exist (fun m : nat => S n' = S m) n' (pred_strong4'_subproof0 n _H)
end
     : forall n : nat, n > 0 -> {m : nat | n = S m}
]]

We are almost done with the ideal implementation of dependent predecessor.  We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment.  In this book, we will not dwell on the details of syntax extensions; the Coq manual gives a straightforward introduction to them. *)

Notation "!" := (False_rec _ _).
Notation "[ e ]" := (exist _ e _).

Definition pred_strong5 : forall n : nat, n > 0 -> {m : nat | n = S m}.
  refine (fun n =>
    match n with
      | O => fun _ => !
      | S n' => fun _ => [n']
    end); crush.
Defined.

(** By default, notations are also used in pretty-printing terms, including results of evaluation. *)

Eval compute in pred_strong5 two_gt0.
(** %\vspace{-.15in}% [[
     = [1]
     : {m : nat | 2 = S m}
     ]]

  One other alternative is worth demonstrating.  Recent Coq versions include a facility called %\index{Program}%[Program] that streamlines this style of definition.  Here is a complete implementation using [Program].%\index{Vernacular commands!Obligation Tactic}\index{Vernacular commands!Program Definition}% *)

Obligation Tactic := crush.

Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=
  match n with
    | O => _
    | S n' => n'
  end.

(** Printing the resulting definition of [pred_strong6] yields a term very similar to what we built with [refine].  [Program] can save time in writing programs that use subset types.  Nonetheless, [refine] is often just as effective, and [refine] gives more control over the form the final term takes, which can be useful when you want to prove additional theorems about your definition.  [Program] will sometimes insert type casts that can complicate theorem proving. *)

Eval compute in pred_strong6 two_gt0.
(** %\vspace{-.15in}% [[
     = [1]
     : {m : nat | 2 = S m}
     ]]

In this case, we see that the new definition yields the same computational behavior as before. *)

(** * Decidable Proposition Types *)

(** There is another type in the standard library that captures the idea of program values that indicate which of two propositions is true.%\index{Gallina terms!sumbool}% *)

Print sumbool.
(** %\vspace{-.15in}% [[
Inductive sumbool (A : Prop) (B : Prop) : Set :=
    left : A -> {A} + {B} | right : B -> {A} + {B}
]]

Here, the constructors of [sumbool] have types written in terms of a registered notation for [sumbool], such that the result type of each constructor desugars to [sumbool A B].  We can define some notations of our own to make working with [sumbool] more convenient. *)

Notation "'Yes'" := (left _ _).
Notation "'No'" := (right _ _).
Notation "'Reduce' x" := (if x then Yes else No) (at level 50).

(** The %\coqdocnotation{%#<tt>#Reduce#</tt>#%}% notation is notable because it demonstrates how [if] is overloaded in Coq.  The [if] form actually works when the test expression has any two-constructor inductive type.  Moreover, in the [then] and [else] branches, the appropriate constructor arguments are bound.  This is important when working with [sumbool]s, when we want to have the proof stored in the test expression available when proving the proof obligations generated in the appropriate branch.

Now we can write [eq_nat_dec], which compares two natural numbers, returning either a proof of their equality or a proof of their inequality. *)

Definition eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.
  refine (fix f (n m : nat) : {n = m} + {n <> m} :=
    match n, m with
      | O, O => Yes
      | S n', S m' => Reduce (f n' m')
      | _, _ => No
    end); congruence.
Defined.

Eval compute in eq_nat_dec 2 2.
(** %\vspace{-.15in}% [[
     = Yes
     : {2 = 2} + {2 <> 2}
     ]]
     *)

Eval compute in eq_nat_dec 2 3.
(** %\vspace{-.15in}% [[
     = No
     : {2 = 3} + {2 <> 3}
     ]]

Note that the %\coqdocnotation{%#<tt>#Yes#</tt>#%}% and %\coqdocnotation{%#<tt>#No#</tt>#%}% notations are hiding proofs establishing the correctness of the outputs.

   Our definition extracts to reasonable OCaml code. *)

Extraction eq_nat_dec.

(** %\begin{verbatim}
(** val eq_nat_dec : nat -> nat -> sumbool **)

let rec eq_nat_dec n m =
  match n with
    | O -> (match m with
              | O -> Left
              | S n0 -> Right)
    | S n' -> (match m with
                 | O -> Right
                 | S m' -> eq_nat_dec n' m')
\end{verbatim}%

#

(** val eq_nat_dec : nat -> nat -> sumbool **)

let rec eq_nat_dec n m =
  match n with
    | O -> (match m with
              | O -> Left
              | S n0 -> Right)
    | S n' -> (match m with
                 | O -> Right
                 | S m' -> eq_nat_dec n' m')

#

Proving this kind of decidable equality result is so common that Coq comes with a tactic for automating it.%\index{tactics!decide equality}% *)

Definition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.
  decide equality.
Defined.

(** Curious readers can verify that the [decide equality] version extracts to the same OCaml code as our more manual version does.  That OCaml code had one undesirable property, which is that it uses <<Left>> and <<Right>> constructors instead of the Boolean values built into OCaml.  We can fix this, by using Coq's facility for mapping Coq inductive types to OCaml variant types.%\index{Vernacular commands!Extract Inductive}% *)

Extract Inductive sumbool => "bool" ["true" "false"].
Extraction eq_nat_dec'.

(** %\begin{verbatim}
(** val eq_nat_dec' : nat -> nat -> bool **)

let rec eq_nat_dec' n m0 =
  match n with
    | O -> (match m0 with
              | O -> true
              | S n0 -> false)
    | S n0 -> (match m0 with
                 | O -> false
                 | S n1 -> eq_nat_dec' n0 n1)
\end{verbatim}%

#

(** val eq_nat_dec' : nat -> nat -> bool **)

let rec eq_nat_dec' n m0 =
  match n with
    | O -> (match m0 with
              | O -> true
              | S n0 -> false)
    | S n0 -> (match m0 with
                 | O -> false
                 | S n1 -> eq_nat_dec' n0 n1)

# *)

(** %\smallskip%

We can build "smart" versions of the usual Boolean operators and put them to good use in certified programming.  For instance, here is a [sumbool] version of Boolean "or." *)

(* EX: Write a function that decides if an element belongs to a list. *)

(* begin thide *)
Notation "x || y" := (if x then Yes else Reduce y).

(** Let us use it for building a function that decides list membership.  We need to assume the existence of an equality decision procedure for the type of list elements. *)

Section In_dec.
  Variable A : Set.
  Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.

  (** The final function is easy to write using the techniques we have developed so far. *)

  Definition In_dec : forall (x : A) (ls : list A), {In x ls} + {~ In x ls}.
    refine (fix f (x : A) (ls : list A) : {In x ls} + {~ In x ls} :=
      match ls with
	| nil => No
	| x' :: ls' => A_eq_dec x x' || f x ls'
      end); crush.
  Defined.
End In_dec.

Eval compute in In_dec eq_nat_dec 2 (1 :: 2 :: nil).
(** %\vspace{-.15in}% [[
     = Yes
     : {In 2 (1 :: 2 :: nil)} + { ~ In 2 (1 :: 2 :: nil)}
     ]]
     *)

Eval compute in In_dec eq_nat_dec 3 (1 :: 2 :: nil).
(** %\vspace{-.15in}% [[
     = No
     : {In 3 (1 :: 2 :: nil)} + { ~ In 3 (1 :: 2 :: nil)}
     ]]

The [In_dec] function has a reasonable extraction to OCaml. *)

Extraction In_dec.
(* end thide *)

(** %\begin{verbatim}
(** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)

let rec in_dec a_eq_dec x = function
  | Nil -> false
  | Cons (x', ls') ->
      (match a_eq_dec x x' with
         | true -> true
         | false -> in_dec a_eq_dec x ls')
\end{verbatim}%

#

(** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **)

let rec in_dec a_eq_dec x = function
  | Nil -> false
  | Cons (x', ls') ->
      (match a_eq_dec x x' with
         | true -> true
         | false -> in_dec a_eq_dec x ls')

#

This is more or the less code for the corresponding function from the OCaml standard library. *)

(** * Partial Subset Types *)

(** Our final implementation of dependent predecessor used a very specific argument type to ensure that execution could always complete normally.  Sometimes we want to allow execution to fail, and we want a more principled way of signaling failure than returning a default value, as [pred] does for [0].  One approach is to define this type family %\index{Gallina terms!maybe}%[maybe], which is a version of [sig] that allows obligation-free failure. *)

Inductive maybe (A : Set) (P : A -> Prop) : Set :=
| Unknown : maybe P
| Found : forall x : A, P x -> maybe P.

(** We can define some new notations, analogous to those we defined for subset types. *)

Notation "{{ x | P }}" := (maybe (fun x => P)).
Notation "??" := (Unknown _).
Notation "[| x |]" := (Found _ x _).

(** Now our next version of [pred] is trivial to write. *)

Definition pred_strong7 : forall n : nat, {{m | n = S m}}.
  refine (fun n =>
    match n return {{m | n = S m}} with
      | O => ??
      | S n' => [|n'|]
    end); trivial.
Defined.

Eval compute in pred_strong7 2.
(** %\vspace{-.15in}% [[
     = [|1|]
     : {{m | 2 = S m}}
      ]]
     *)

Eval compute in pred_strong7 0.
(** %\vspace{-.15in}% [[
     = ??
     : {{m | 0 = S m}}
     ]]

     Because we used [maybe], one valid implementation of the type we gave [pred_strong7] would return [??] in every case.  We can strengthen the type to rule out such vacuous implementations, and the type family %\index{Gallina terms!sumor}%[sumor] from the standard library provides the easiest starting point.  For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *)

Print sumor.
(** %\vspace{-.15in}% [[
Inductive sumor (A : Type) (B : Prop) : Type :=
    inleft : A -> A + {B} | inright : B -> A + {B}
]]

We add notations for easy use of the [sumor] constructors.  The second notation is specialized to [sumor]s whose [A] parameters are instantiated with regular subset types, since this is how we will use [sumor] below. *)

Notation "!!" := (inright _ _).
Notation "[|| x ||]" := (inleft _ [x]).

(** Now we are ready to give the final version of possibly failing predecessor.  The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *)

Definition pred_strong8 : forall n : nat, {m : nat | n = S m} + {n = 0}.
  refine (fun n =>
    match n with
      | O => !!
      | S n' => [||n'||]
    end); trivial.
Defined.

Eval compute in pred_strong8 2.
(** %\vspace{-.15in}% [[
     = [||1||]
     : {m : nat | 2 = S m} + {2 = 0}
     ]]
     *)

Eval compute in pred_strong8 0.
(** %\vspace{-.15in}% [[
     = !!
     : {m : nat | 0 = S m} + {0 = 0}
     ]]
     *)

(** As with our other maximally expressive [pred] function, we arrive at quite simple output values, thanks to notations. *)

(** * Monadic Notations *)

(** We can treat [maybe] like a monad%~\cite{Monads}\index{monad}\index{failure monad}%, in the same way that the Haskell <<Maybe>> type is interpreted as a failure monad.  Our [maybe] has the wrong type to be a literal monad, but a "bind"-like notation will still be helpful.  %Note that the notation definition uses an ASCII \texttt{<-}, while later code uses (in this rendering) a nicer left arrow $\leftarrow$.% *)

Notation "x <- e1 ; e2" := (match e1 with
                             | Unknown => ??
                             | Found x _ => e2
                           end)
(right associativity, at level 60).

(** The meaning of [x <- e1; e2] is: First run [e1].  If it fails to find an answer, then announce failure for our derived computation, too.  If [e1] _does_ find an answer, pass that answer on to [e2] to find the final result.  The variable [x] can be considered bound in [e2].

   This notation is very helpful for composing richly typed procedures.  For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *)

(* EX: Write a function that tries to compute predecessors of two [nat]s at once. *)

(* begin thide *)
Definition doublePred : forall n1 n2 : nat, {{p | n1 = S (fst p) /\ n2 = S (snd p)}}.
  refine (fun n1 n2 =>
    m1 <- pred_strong7 n1;
    m2 <- pred_strong7 n2;
    [|(m1, m2)|]); tauto.
Defined.
(* end thide *)

(** We can build a [sumor] version of the "bind" notation and use it to write a similarly straightforward version of this function.  %Again, the notation definition exposes the ASCII syntax with an operator \texttt{<-{}-}, while the later code uses a nicer long left arrow $\longleftarrow$.% *)

(** %\def\indash{-}\catcode`-=13\def-{\indash\kern0pt }% *)

Notation "x <-- e1 ; e2" := (match e1 with
                               | inright _ => !!
                               | inleft (exist x _) => e2
                             end)
(right associativity, at level 60).

(** %\catcode`-=12% *)(* *)
(** printing * $\times$ *)

(* EX: Write a more expressively typed version of the last exercise. *)

(* begin thide *)
Definition doublePred' : forall n1 n2 : nat,
  {p : nat * nat | n1 = S (fst p) /\ n2 = S (snd p)}
  + {n1 = 0 \/ n2 = 0}.
  refine (fun n1 n2 =>
    m1 <-- pred_strong8 n1;
    m2 <-- pred_strong8 n2;
    [||(m1, m2)||]); tauto.
Defined.
(* end thide *)

(** This example demonstrates how judicious selection of notations can hide complexities in the rich types of programs. *)

(** * A Type-Checking Example *)

(** We can apply these specification types to build a certified type checker for a simple expression language. *)

Inductive exp : Set :=
| Nat : nat -> exp
| Plus : exp -> exp -> exp
| Bool : bool -> exp
| And : exp -> exp -> exp.

(** We define a simple language of types and its typing rules, in the style introduced in Chapter 4. *)

Inductive type : Set := TNat | TBool.

Inductive hasType : exp -> type -> Prop :=
| HtNat : forall n,
  hasType (Nat n) TNat
| HtPlus : forall e1 e2,
  hasType e1 TNat
  -> hasType e2 TNat
  -> hasType (Plus e1 e2) TNat
| HtBool : forall b,
  hasType (Bool b) TBool
| HtAnd : forall e1 e2,
  hasType e1 TBool
  -> hasType e2 TBool
  -> hasType (And e1 e2) TBool.

(** It will be helpful to have a function for comparing two types.  We build one using [decide equality]. *)

(* begin thide *)
Definition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.
  decide equality.
Defined.

(** Another notation complements the monadic notation for [maybe] that we defined earlier.  Sometimes we want to include "assertions" in our procedures.  That is, we want to run a decision procedure and fail if it fails; otherwise, we want to continue, with the proof that it produced made available to us.  This infix notation captures that idea, for a procedure that returns an arbitrary two-constructor type. *)

Notation "e1 ;; e2" := (if e1 then e2 else ??)
  (right associativity, at level 60).

(** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations.  Every [[|e|]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *)
(* end thide *)

Definition typeCheck : forall e : exp, {{t | hasType e t}}.
(* begin thide *)
  Hint Constructors hasType.

  refine (fix F (e : exp) : {{t | hasType e t}} :=
    match e return {{t | hasType e t}} with
      | Nat _ => [|TNat|]
      | Plus e1 e2 =>
        t1 <- F e1;
        t2 <- F e2;
        eq_type_dec t1 TNat;;
        eq_type_dec t2 TNat;;
        [|TNat|]
      | Bool _ => [|TBool|]
      | And e1 e2 =>
        t1 <- F e1;
        t2 <- F e2;
        eq_type_dec t1 TBool;;
        eq_type_dec t2 TBool;;
        [|TBool|]
    end); crush.
(* end thide *)
Defined.

(** Despite manipulating proofs, our type checker is easy to run. *)

Eval simpl in typeCheck (Nat 0).
(** %\vspace{-.15in}% [[
     = [|TNat|]
     : {{t | hasType (Nat 0) t}}
     ]]
     *)

Eval simpl in typeCheck (Plus (Nat 1) (Nat 2)).
(** %\vspace{-.15in}% [[
     = [|TNat|]
     : {{t | hasType (Plus (Nat 1) (Nat 2)) t}}
     ]]
     *)

Eval simpl in typeCheck (Plus (Nat 1) (Bool false)).
(** %\vspace{-.15in}% [[
     = ??
     : {{t | hasType (Plus (Nat 1) (Bool false)) t}}
     ]]

The type checker also extracts to some reasonable OCaml code. *)

Extraction typeCheck.

(** %\begin{verbatim}
(** val typeCheck : exp -> type0 maybe **)

let rec typeCheck = function
  | Nat n -> Found TNat
  | Plus (e1, e2) ->
      (match typeCheck e1 with
         | Unknown -> Unknown
         | Found t1 ->
             (match typeCheck e2 with
                | Unknown -> Unknown
                | Found t2 ->
                    (match eq_type_dec t1 TNat with
                       | true ->
                           (match eq_type_dec t2 TNat with
                              | true -> Found TNat
                              | false -> Unknown)
                       | false -> Unknown)))
  | Bool b -> Found TBool
  | And (e1, e2) ->
      (match typeCheck e1 with
         | Unknown -> Unknown
         | Found t1 ->
             (match typeCheck e2 with
                | Unknown -> Unknown
                | Found t2 ->
                    (match eq_type_dec t1 TBool with
                       | true ->
                           (match eq_type_dec t2 TBool with
                              | true -> Found TBool
                              | false -> Unknown)
                       | false -> Unknown)))
\end{verbatim}%

#

(** val typeCheck : exp -> type0 maybe **)

let rec typeCheck = function
  | Nat n -> Found TNat
  | Plus (e1, e2) ->
      (match typeCheck e1 with
         | Unknown -> Unknown
         | Found t1 ->
             (match typeCheck e2 with
                | Unknown -> Unknown
                | Found t2 ->
                    (match eq_type_dec t1 TNat with
                       | true ->
                           (match eq_type_dec t2 TNat with
                              | true -> Found TNat
                              | false -> Unknown)
                       | false -> Unknown)))
  | Bool b -> Found TBool
  | And (e1, e2) ->
      (match typeCheck e1 with
         | Unknown -> Unknown
         | Found t1 ->
             (match typeCheck e2 with
                | Unknown -> Unknown
                | Found t2 ->
                    (match eq_type_dec t1 TBool with
                       | true ->
                           (match eq_type_dec t2 TBool with
                              | true -> Found TBool
                              | false -> Unknown)
                       | false -> Unknown)))

# *)

(** %\smallskip%

We can adapt this implementation to use [sumor], so that we know our type-checker only fails on ill-typed inputs.  First, we define an analogue to the "assertion" notation. *)

(* begin thide *)
Notation "e1 ;;; e2" := (if e1 then e2 else !!)
  (right associativity, at level 60).

(** Next, we prove a helpful lemma, which states that a given expression can have at most one type. *)

Lemma hasType_det : forall e t1,
  hasType e t1
  -> forall t2, hasType e t2
    -> t1 = t2.
  induction 1; inversion 1; crush.
Qed.

(** Now we can define the type-checker.  Its type expresses that it only fails on untypable expressions. *)

(* end thide *)
Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}.
(* begin thide *)
  Hint Constructors hasType.

  (** We register all of the typing rules as hints. *)

  Hint Resolve hasType_det.

  (** The lemma [hasType_det] will also be useful for proving proof obligations with contradictory contexts.  Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *)

  (** Finally, the implementation of [typeCheck] can be transcribed literally, simply switching notations as needed. *)

  refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} :=
    match e return {t : type | hasType e t} + {forall t, ~ hasType e t} with
      | Nat _ => [||TNat||]
      | Plus e1 e2 =>
        t1 <-- F e1;
        t2 <-- F e2;
        eq_type_dec t1 TNat;;;
        eq_type_dec t2 TNat;;;
        [||TNat||]
      | Bool _ => [||TBool||]
      | And e1 e2 =>
        t1 <-- F e1;
        t2 <-- F e2;
        eq_type_dec t1 TBool;;;
        eq_type_dec t2 TBool;;;
        [||TBool||]
    end); clear F; crush' tt hasType; eauto.

  (** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make.  Such a step is usually warranted when defining a recursive function with [refine].  The [crush] variant %\index{tactics!crush'}%[crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument.  Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *)
(* end thide *)

Defined.

(** The short implementation here hides just how time-saving automation is.  Every use of one of the notations adds a proof obligation, giving us 12 in total.  Most of these obligations require multiple inversions and either uses of [hasType_det] or applications of [hasType] rules.

   Our new function remains easy to test: *)

Eval simpl in typeCheck' (Nat 0).
(** %\vspace{-.15in}% [[
     = [||TNat||]
     : {t : type | hasType (Nat 0) t} +
       {(forall t : type, ~ hasType (Nat 0) t)}
       ]]
       *)

Eval simpl in typeCheck' (Plus (Nat 1) (Nat 2)).
(** %\vspace{-.15in}% [[
     = [||TNat||]
     : {t : type | hasType (Plus (Nat 1) (Nat 2)) t} +
       {(forall t : type, ~ hasType (Plus (Nat 1) (Nat 2)) t)}
       ]]
       *)

Eval simpl in typeCheck' (Plus (Nat 1) (Bool false)).
(** %\vspace{-.15in}% [[
     = !!
     : {t : type | hasType (Plus (Nat 1) (Bool false)) t} +
       {(forall t : type, ~ hasType (Plus (Nat 1) (Bool false)) t)}
       ]]

The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *)


Require Import Coq.Classes.RelationClasses.

Set Implicit Arguments.
Set Strict Implicit.

Fixpoint guard A (R : A -> A -> Prop) (n : nat) (wfR : well_founded R)
  {struct n}: well_founded R :=
  match n with
    | 0 => wfR
    | S n => fun x => Acc_intro x (fun y _ => guard n (guard n wfR) y)
  end.

Section setoid_fix.
  Variables (A : Type) (R : A -> A -> Prop) (Rwf : well_founded R).
  Variables (P : A -> Type)
            (F : forall x : A, (forall y : A, R y x -> P y) -> P x).
  Variable r : forall x : A, P x -> P x -> Prop.
  Hypothesis Hstep : forall (x : A) (f g : forall y : A, R y x -> P y),
                       (forall (y : A) (p : R y x), r (f y p) (g y p)) ->
                       r (@F x f) (@F x g).

  Lemma Fix_F_equiv_inv
  : forall (x : A) (r' s' : Acc R x),
      r (Fix_F _ F r') (Fix_F _ F s').
  Proof.
    intro x; induction (Rwf x); intros.
    rewrite <- (Fix_F_eq _ F r'); rewrite <- (Fix_F_eq _ F s'); intros.
    eapply Hstep.
    eauto.
  Qed.

  Theorem Fix_equiv
  : forall x : A,
      r (Fix Rwf P F x) (@F x (fun (y : A) (_ : R y x) => Fix Rwf P F y)).
  Proof.
    intro x; unfold Fix.
    rewrite <- Fix_F_eq.
    apply Hstep; intros.
    apply Fix_F_equiv_inv.
  Qed.
End setoid_fix.


(** * Preservation *)

From DEZ.Is Require Export
  Fixed Commutative Distributive.

(** ** Function Preserving a Nullary Operation *)

Class IsNullPres (A B : Type) (X : B -> B -> Prop)
  (x : A) (y : B) (f : A -> B) : Prop :=
  null_pres : X (f x) y.

Section Context.

Context (A : Type) (X : A -> A -> Prop)
  (x : A) (f : A -> A).

(** Preservation of a nullary operation
    is a special case of the fixed point property. *)

#[export] Instance fixed_is_null_pres
  `{!IsFixed X x f} : IsNullPres X x x f.
Proof. auto. Qed.

#[local] Instance null_pres_is_fixed
  `{!IsNullPres X x x f} : IsFixed X x f.
Proof. auto. Qed.

End Context.

(** ** Function Preserving a Unary Operation *)

Class IsUnPres (A B : Type) (X : B -> B -> Prop)
  (f : A -> A) (g : B -> B) (h : A -> B) : Prop :=
  un_pres (x : A) : X (h (f x)) (g (h x)).

Section Context.

Context (A : Type) (X : A -> A -> Prop)
  (f g : A -> A).

(** Preservation of a unary operation
    is a special case of the commutative property. *)

#[export] Instance comm_un_ops_is_un_pres
  `{!IsCommUnOps X f g} : IsUnPres X g g f.
Proof. auto. Qed.

#[local] Instance un_pres_is_comm_un_ops
  `{!IsUnPres X g g f} : IsCommUnOps X f g.
Proof. auto. Qed.

End Context.

(** ** Function Preserving a Binary Operation *)

Class IsBinPres (A B : Type) (X : B -> B -> Prop)
  (k : A -> A -> A) (m : B -> B -> B) (f : A -> B) : Prop :=
  bin_pres (x y : A) : X (f (k x y)) (m (f x) (f y)).

Section Context.

Context (A B : Type) (X : B -> B -> Prop)
  (f : A -> B) (k : A -> A -> A) (m : B -> B -> B).

(** Preservation of a binary operation
    is a special case of the distributive property. *)

#[export] Instance distr_un_fn_is_bin_pres
  `{!IsDistrUnFn X f k m} : IsBinPres X k m f.
Proof. auto. Qed.

#[local] Instance bin_pres_is_distr_un_fn
  `{!IsBinPres X k m f} : IsDistrUnFn X f k m.
Proof. auto. Qed.

End Context.