Require Import EqStuff.
Require Import Le Lt.

(* Semantic type-level contexts, as left nested sigmas *)

(* Strongly typed de Bruijn indexes:
 * Allow you to project from an environment, n steps from the near end.
 *)
Inductive AtTCtx : forall D,nat->(D->Type)->Type :=
	topTCtx D (T:D->Type) : AtTCtx (sigT T) O (fun d=>T (projT1 d)) |
	popTCtx D n T T' : AtTCtx D n T->AtTCtx (sigT T') (S n) (fun d=>T (projT1 d)).
Implicit Arguments topTCtx [D].
Implicit Arguments popTCtx [D n T].

(* Project from an environment *)
Fixpoint tctxProj D n T (f:AtTCtx D n T) : forall d,T d := match f with
	topTCtx _ _ => @projT2 _ _ |
	popTCtx _ _ _ _ f => fun d=>tctxProj _ _ _ f (projT1 d)
end.
Implicit Arguments tctxProj [D n T].

(* Semantic contexts (in a type-level context) *)

Inductive CtxS D : (D->Type)->Type :=
	empCtxS : CtxS D (fun d=>unit) |
	extCtxS G : CtxS D G->forall T:forall d,G d->Type,CtxS D (fun d=>sigT (T d)).
Implicit Arguments CtxS [D].
Implicit Arguments extCtxS [D G].

Inductive Ctx D : Type := ctx (G:D->Type) (s:CtxS G).
Implicit Arguments ctx [D G].

Definition ctxTp D (G:Ctx D) := match G with ctx G _ => G end.
Implicit Arguments ctxTp [D].
Coercion ctxTp : Ctx >-> Funclass.

Definition ctxSc D (G:Ctx D) : CtxS G := match G with ctx _ s => s end.
Implicit Arguments ctxSc [D].

Definition empCtx D := ctx (empCtxS D).
Definition extCtx D (G:Ctx D) (T:forall d,G d->Type) := ctx (extCtxS (ctxSc G) T).
Implicit Arguments extCtx [D].

Definition CtxNEmp D (G:Ctx D) := match G with
	ctx _ empCtxS => False |
	ctx _ (extCtxS _ _ _) => True
end.
Implicit Arguments CtxNEmp [D].

Definition ctxInit D G := match G with
	ctx _ empCtxS => empCtx D |
	ctx _ (extCtxS _ s _) => ctx s
end.
Implicit Arguments ctxInit [D].

Definition ctxTop D (G:Ctx D) : forall d,ctxInit G d->Type.
	destruct G.
	destruct s;simpl.

	exact (fun d g=>unit).

	exact T.
Defined.
Implicit Arguments ctxTop [D].

Definition extCtxUnfold D (G:Ctx D) : forall ne:CtxNEmp G,G = extCtx (ctxInit G) (ctxTop G).
	destruct G.
	destruct s;simpl;intro.

	exact (match ne with end).

	reflexivity.
Defined.
Implicit Arguments extCtxUnfold [D G].

Definition extCtxInj D (G1 G2:Ctx D) : forall T1 T2 (e:extCtx G1 T1 = extCtx G2 T2),
existT (fun G:Ctx D=>forall d,G d->Type) G1 T1 = existT _ G2 T2.
	destruct G1 as (G1,s1).
	destruct G2 as (G2,s2).
	simpl.
	intros.
	exact (tr (fun Gx=>_ = existT _ _ (ctxTop Gx)) e (eq_refl _)).
Defined.
Implicit Arguments extCtxInj [D G1 G2 T1 T2].

Inductive AtCtx D : forall G:Ctx D,nat->(forall d,G d->Type)->Type :=
	topCtx G T : AtCtx D (extCtx G T) O (fun d g=>T d (projT1 g)) |
	popCtx G n T : AtCtx D G n T->forall T',AtCtx D (extCtx G T') (S n) (fun d g=>T d (projT1 g)).
Implicit Arguments AtCtx [D].
Implicit Arguments topCtx [D].
Implicit Arguments popCtx [D G n T].

Definition topCtxInv_ext D (G:Ctx D) T' T (a:AtCtx (extCtx G T') O T) (P:forall G T' n T,AtCtx (extCtx G T') n T->Type)
	(top:P _ _ _ _ (topCtx G T'))
: P _ _ _ _ a.
	pose (P' Gx n T (a:AtCtx Gx n T) := forall ne:CtxNEmp Gx,
		P _ _ _ _ (projT2 (tr (fun G=>sigT (AtCtx G n)) (extCtxUnfold ne) (existT _ _ a)))).
	assert (Peq := match G as G return forall T' T a,P G T' O T a = P (ctx (ctxSc G)) _ _ _ a
		with ctx _ _ => fun _ _ _=>eq_refl _ end T').
	apply (tr (fun C=>C) (eq_sym (Peq _ _))).
	generalize I.
	change (P' _ _ _ a).
	refine (match a as a in AtCtx Gx zro T return (O = zro)->(extCtx G T' = Gx)->P' _ _ _ a with
		topCtx _ _ => fun Hn HG=>_ |
		popCtx _ _ _ _ _ => fun e=>match O_S _ e with end
	end (eq_refl _) (eq_refl _)).
	apply (tr (fun GT'=>P' _ _ _ (topCtx (projT1 GT') (projT2 GT'))) (extCtxInj HG)).
	simpl.
	intro.
	simpl.
	exact (tr (fun C=>C) (Peq _ _) top).
Defined.
Implicit Arguments topCtxInv_ext [D G T' T].

Definition topCtxInv_extEq D (G:Ctx D) T P := match G
return forall T top,topCtxInv_ext (topCtx G T) P top = top
	with ctx _ _ => fun _ _=>eq_refl _ end T.
Implicit Arguments topCtxInv_extEq [D G T].

Definition popCtxInv_ext D (G:Ctx D) T' n T (a:AtCtx (extCtx G T') (S n) T) (P:forall G T' n T,AtCtx (extCtx G T') n T->Type)
	(pop:forall T (a:AtCtx G n T),P _ _ _ _ (popCtx a T'))
: P _ _ _ _ a.
	pose (P' Gx n T (a:AtCtx Gx n T) := forall ne:CtxNEmp Gx,
		P _ _ _ _ (projT2 (tr (fun G=>sigT (AtCtx G n)) (extCtxUnfold ne) (existT _ _ a)))).
	assert (Peq := match G as G return forall T' T a,P G T' (S n) T a = P (ctx (ctxSc G)) _ _ _ a
		with ctx _ _ => fun _ _ _=>eq_refl _ end T').
	apply (tr (fun C=>C) (eq_sym (Peq _ _))).
	generalize I.
	change (P' _ _ _ a).
	refine (match a as a in AtCtx Gx Sn T return (Sn = S n)->(extCtx G T' = Gx)->P' _ _ _ a with
		topCtx _ _ => fun e=>match O_S _ e with end |
		popCtx _ _ T0 a0 _ => fun Hn HG=>_
	end (eq_refl _) (eq_refl _)).
	revert T0 a0.
	apply (tr (fun _=>_) (eq_sym (Sinj Hn))).
	apply (tr (fun GT'=>forall T (a:AtCtx _ _ T),P' _ _ _ (popCtx a (projT2 GT'))) (extCtxInj HG)).
	simpl.
	intros ? ? ?.
	simpl.
	exact (tr (fun C=>C) (Peq _ _) (pop _ _)).
Defined.
Implicit Arguments popCtxInv_ext [D G T' n T].

Definition popCtxInv_extEq D (G:Ctx D) T' n T a P := match G
return forall T' T (a:AtCtx G n T) pop,popCtxInv_ext (popCtx a T') P pop = pop T a
	with ctx _ _ => fun _ _ _ _=>eq_refl _ end T' T a.
Implicit Arguments popCtxInv_extEq [D G T' n T].

Fixpoint ctxProj D (G:Ctx D) n T (a:AtCtx G n T) d : forall g,T d g := match a with
	topCtx _ _ => @projT2 _ _ |
	popCtx _ _ _ a _ => fun g=>ctxProj _ _ _ _ a _ (projT1 g)
end.
Implicit Arguments ctxProj [D G n T].

Definition atCtxEta D (G:Ctx D) n T (a:AtCtx G n T) : AtCtx G n (fun d g=>T d g) := match a with
	topCtx _ _ => topCtx _ _ |
	popCtx _ _ _ a _ => popCtx a _
end.
Implicit Arguments atCtxEta [D G n T].

Lemma ctxProj_Eta D (G:Ctx D) n T (a:AtCtx G n T) : ctxProj (atCtxEta a) = fun d g=>ctxProj a d g.
	destruct a;reflexivity.
Qed.

(* Weaken for a new type-level context entry *)

Fixpoint ctxSBumpD D (F G:D->Type) (s:CtxS G) : CtxS (fun d:sigT F=>G (projT1 d)) := match s with
	empCtxS => empCtxS _ |
	extCtxS _ s _ => extCtxS (ctxSBumpD _ _ _ s) _
end.
Implicit Arguments ctxSBumpD [D G].

Definition ctxBumpD D (F:D->Type) (G:Ctx D) := ctx (ctxSBumpD F (ctxSc G)).
Implicit Arguments ctxBumpD [D].

Fixpoint atBumpD D (F:D->Type) G n T (a:AtCtx G n T) :
AtCtx (ctxBumpD F G) n (fun d=>T (projT1 d)) := match a with
	topCtx G _ => topCtx (ctxBumpD F G) _ |
	popCtx _ _ _ a _ => popCtx (atBumpD _ _ _ _ _ a) _
end.
Implicit Arguments atBumpD [D G n T].

Lemma ctxProj_BumpD D F (G:Ctx D) n T (a:AtCtx G n T) : ctxProj (atBumpD F a) = fun d=>ctxProj a (projT1 d).
	induction a.

	reflexivity.

	simpl.
	rewrite IHa.
	reflexivity.
Qed.

(* Iterated context extension *)

Inductive ExtCtx D GL : nat->Ctx D->Type :=
	extOCtx : ExtCtx D GL O GL |
	extSCtx n G : ExtCtx D GL n G->forall T:forall d,G d->Type,ExtCtx D GL (S n) (extCtx G T).
Implicit Arguments ExtCtx [D].
Implicit Arguments extOCtx [D].
Implicit Arguments extSCtx [D GL n G].

Definition extOCtxInv D (GL G:Ctx D) (xg:ExtCtx GL O G) (P:forall n G,ExtCtx GL n G->Type)
	(xgO:P O GL (extOCtx GL))
: P _ _ xg := match xg in ExtCtx _ zro _ return (O = zro)->P _ _ xg with
	extOCtx => fun _=>xgO |
	extSCtx _ _ _ _ => fun e=>match O_S _ e with end
end (eq_refl _).
Implicit Arguments extOCtxInv [D GL G].

Definition extSCtxInv D (GL:Ctx D) n G (xg:ExtCtx GL (S n) G) (P:forall n G,ExtCtx GL n G->Type)
	(xgS:forall G (xg:ExtCtx GL n G) T,P _ _ (extSCtx xg T))
: P _ _ xg.
	refine (match xg as xg in ExtCtx _ Sn _ return (Sn = S n)->P _ _ xg with
		extOCtx => fun e=>match O_S _ e with end |
		extSCtx _ _ xg0 _ => fun e=>_
	end (eq_refl _)).
	exact (match eq_sym (Sinj e) return _ with eq_refl => xgS _ end xg0 _).
Defined.
Implicit Arguments extSCtxInv [D GL n G].

(* Induction on the number of added entries *)
Definition extCtxNInd D (GL:Ctx D) (P:forall n G,ExtCtx GL n G->Type)
	(xgO:P _ _ (extOCtx GL))
	(xgS:forall n,(forall G (xg:ExtCtx GL n G),P _ _ xg)->
		forall G (xg:ExtCtx GL n G) T,P _ _ (extSCtx xg T))
: forall n G (xg:ExtCtx GL n G),P _ _ xg.
	refine (fix extCtxNInd n G := match n with
		O => fun xg=>_ |
		S _ => fun xg=>_
	end).

	exact (extOCtxInv xg _ xgO).

	exact (extSCtxInv xg _ (xgS _ (extCtxNInd _))).
Defined.
Implicit Arguments extCtxNInd [D GL n G].

Definition extSCtxInv_ext D (GL:Ctx D) n G T (xg:ExtCtx GL (S n) (extCtx G T)) (P:forall n G T,ExtCtx GL n (extCtx G T)->Type)
	(xgS:forall xg:ExtCtx GL n G,P _ _ _ (extSCtx xg T))
: P _ _ _ xg.
	pose (P' n Gx (xg:ExtCtx GL n Gx) := forall ne:CtxNEmp Gx,
		P _ _ _ (tr (ExtCtx GL n) (extCtxUnfold ne) xg)).
	assert (Peq := match G as G return forall T xg,P (S n) G T xg = P _ (ctx (ctxSc G)) _ xg
		with ctx _ _ => fun _ _=>eq_refl _ end T).
	apply (tr (fun C=>C) (eq_sym (Peq _))).
	generalize I.
	change (P' _ _ xg).
	refine (match xg as xg in ExtCtx _ Sn Gx return (Sn = S n)->(extCtx G T = Gx)->P' _ _ xg with
		extOCtx => fun e=>match O_S _ e with end |
		extSCtx _ _ xg0 _ => fun Hn HG=>_
	end (eq_refl _) (eq_refl _)).
	revert xg0.
	apply (tr (fun _=>_) (eq_sym (Sinj Hn))).
	apply (tr (fun GT=>forall xg,P' _ _ (extSCtx xg (projT2 GT))) (extCtxInj HG)).
	simpl.
	intros ? ?.
	simpl.
	exact (tr (fun C=>C) (Peq _) (xgS _)).
Defined.
Implicit Arguments extSCtxInv_ext [D GL n G T].

Definition extSCtxInv_extEq D (GL:Ctx D) n G T xg P := match G
return forall T (xg:ExtCtx GL n G) xgS,extSCtxInv_ext (extSCtx xg T) P xgS = xgS xg
	with ctx _ _ => fun _ _ _=>eq_refl _ end T xg.
Implicit Arguments extSCtxInv_extEq [D GL n G T].

Lemma extAtCtxInd D (GL:Ctx D) P (C:forall n G P',ExtCtx (extCtx GL P) n G->AtCtx G n P'->Type)
	(xgO:C _ _ _ (extOCtx _) (topCtx GL P))
	(xgS:forall n G P' xg (a:AtCtx G n P') T,C _ _ _ xg a->C _ _ _ (extSCtx xg T) (popCtx a T))
n G (xg:ExtCtx (extCtx GL P) n G) : forall P' (a:AtCtx G n P'),C _ _ _ xg a.
	induction xg;intros.

	clear xgS.
	assert (z : IsO O).
		exact I.
	revert z C xgO.
	apply (topCtxInv_ext a (fun GL P n _ a=>forall (z:IsO n)
		(C:forall n G P',ExtCtx (extCtx GL P) n G->AtCtx G n P'->Type) xgO,
		C _ _ _ (extOCtx _) (tr (fun n=>AtCtx _ n _) (OUnfold z) a))).
	simpl.
	intros _ ? ?.
	exact xgO.

	assert (nz : IsS (S n)).
		exact I.
	revert nz xg IHxg.
	apply (popCtxInv_ext a (fun _ _ n _ a=>forall (nz:IsS n) xg (IHxg:forall P' a,C _ _ _ xg a),
		C _ _ _ (extSCtx xg _) (tr (fun n=>AtCtx _ n _) (SUnfold nz) a))).
	clear P' a.
	simpl.
	intros P' ? _ ? ?.
	apply xgS.
	apply IHxg.
Qed.

Inductive ExtCtxComp D GL' n G : Type := mkExtCtxComp (G':Ctx D) (xg':ExtCtx GL' n G') (f':forall d,G' d->G d).
Implicit Arguments ExtCtxComp [D].
Implicit Arguments mkExtCtxComp [D GL' n G G'].

Definition xc_G' D (GL':Ctx D) n G (xc:ExtCtxComp GL' n G) := match xc with mkExtCtxComp G' _ _ => G' end.
Implicit Arguments xc_G' [D GL' n G].

Definition xc_xg' D (GL':Ctx D) n G (xc:ExtCtxComp GL' n G) : ExtCtx GL' n (xc_G' xc) := match xc with mkExtCtxComp _ xg' _ => xg' end.
Implicit Arguments xc_xg' [D GL' n G].

Definition xc_f' D (GL':Ctx D) n G (xc:ExtCtxComp GL' n G) : forall d,xc_G' xc d->G d := match xc with mkExtCtxComp _ _ f' => f' end.
Implicit Arguments xc_f' [D GL' n G].

Definition extCtxComp D GL n G (xg:ExtCtx GL n G) (GL':Ctx D) (f:forall d,GL' d->GL d) : ExtCtxComp GL' n G.
	revert n G xg.
	refine (fix extCtxComp n G xg := match xg in ExtCtx _ n G return ExtCtxComp GL' n G with
		extOCtx => _ |
		extSCtx _ _ xg0 T => _
	end).

	exact (mkExtCtxComp (extOCtx _) f).

	pose (xc := extCtxComp _ _ xg0).
	exact (mkExtCtxComp (extSCtx (xc_xg' xc) _)
		(fun d (g:sigT (fun g=>T d (_ d g)))=>existT _ (xc_f' xc d (projT1 g)) (projT2 g))).
Defined.
Implicit Arguments extCtxComp [D GL n G].

Definition xgBumpG D (GL:Ctx D) P l G (xg:ExtCtx GL l G) := extCtxComp xg (extCtx GL P) (fun d=>@projT1 _ _).
Implicit Arguments xgBumpG [D GL l G].

Definition ctxBumpG D (GL:Ctx D) P l G (xg:ExtCtx GL l G) := xc_G' (xgBumpG P xg).
Implicit Arguments ctxBumpG [D GL l G].

Definition elBumpG D (GL:Ctx D) P l G (xg:ExtCtx GL l G) T (F:forall d (g:G d),T d g) d (g:ctxBumpG P xg d) :=
	F d (xc_f' (xgBumpG P xg) d g).
Implicit Arguments elBumpG [D GL l G T].

Definition atBumpGLo D (GL:Ctx D) P l G n T (xg:ExtCtx GL l G) (a:AtCtx G n T) (Ho:n < l) : AtCtx (ctxBumpG P xg) n (elBumpG P xg T).
	revert l Ho xg.
	induction a;intro;(destruct l;intro;[exact (match lt_n_O _ Ho with end) |]);intro.

	apply (extSCtxInv_ext xg).
	clear xg.
	intro.
	unfold ctxBumpG.
	simpl.
	apply topCtx.

	revert T a IHa.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	change (AtCtx (extCtx (ctxBumpG P xg) (elBumpG P xg T')) (S n) (fun d g=>elBumpG P xg T d (projT1 g))).
	apply popCtx.
	exact (IHa _ (lt_S_n _ _ Ho) xg).
Defined.
Implicit Arguments atBumpGLo [D GL l G n T].

Definition atBumpGHi D (GL:Ctx D) P l G n T (xg:ExtCtx GL l G) (a:AtCtx G n T) (Ho:l <= n) : AtCtx (ctxBumpG P xg) (S n) (elBumpG P xg T).
	revert n Ho T a.
	induction xg as [| l ? ? ? T'].

	intros.
	unfold ctxBumpG.
	simpl.
	apply (popCtx a).

	intro.
	destruct n.
		intro.
		exact (match le_Sn_O _ Ho with end).
	intros.
	revert xg IHxg.
	apply (popCtxInv_ext a (fun _ _ _ _ _=>_)).
	clear T a.
	intros.
	change (AtCtx (extCtx (ctxBumpG P xg) (elBumpG P xg T')) (S (S n)) (fun d g=>elBumpG P xg T d (projT1 g))).
	apply popCtx.
	exact (IHxg _ (le_S_n _ _ Ho) _ a).
Defined.
Implicit Arguments atBumpGHi [D GL l G n T].

Lemma ctxProj_BumpGLo D (GL:Ctx D) P l G n T (xg:ExtCtx GL l G) (a:AtCtx G n T) (Ho:n < l) :
ctxProj (atBumpGLo P xg a Ho) = elBumpG P xg (ctxProj a).
	revert l Ho xg.
	induction a;intro;(destruct l;intro;[exact (match lt_n_O _ Ho with end) |]);intro.

	revert Ho.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	simpl.
	rewrite extSCtxInv_extEq.
	reflexivity.

	revert T a IHa Ho.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	simpl.
	rewrite extSCtxInv_extEq.
	change (ctxProj (popCtx (atBumpGLo P xg a (lt_S_n _ _ Ho)) (elBumpG P xg T')) =
		elBumpG P (extSCtx xg T') (ctxProj (popCtx a T'))).
	simpl.
	rewrite IHa.
	reflexivity.
Qed.

Lemma ctxProj_BumpGHi D (GL:Ctx D) P l G n T (xg:ExtCtx GL l G) (a:AtCtx G n T) (Ho:l <= n) :
ctxProj (atBumpGHi P xg a Ho) = elBumpG P xg (ctxProj a).
	revert n Ho T a.
	induction xg as [| l ? ? ? T'].

	intros.
	reflexivity.

	intro.
	destruct n.
		intro.
		exact (match le_Sn_O _ Ho with end).
	intros.
	revert xg IHxg Ho.
	apply (popCtxInv_ext a).
	clear T a.
	intros.
	simpl.
	rewrite popCtxInv_extEq.
	change (ctxProj (popCtx (atBumpGHi P xg a (le_S_n _ _ Ho)) (elBumpG P xg T')) =
		elBumpG P (extSCtx xg T') (ctxProj (popCtx a T'))).
	simpl.
	rewrite IHxg.
	reflexivity.
Qed.

Definition xgSubst D (GL:Ctx D) P l G (xg:ExtCtx (extCtx GL P) l G) (p:forall d g,P d g) :=
	extCtxComp xg GL (fun d g=>existT _ g (p d g)).
Implicit Arguments xgSubst [D GL P l G].

Definition ctxSubst D (GL:Ctx D) P l G (xg:ExtCtx (extCtx GL P) l G) p := xc_G' (xgSubst xg p).
Implicit Arguments ctxSubst [D GL P l G].

Definition elSubst D (GL:Ctx D) P l G (xg:ExtCtx (extCtx GL P) l G) T (F:forall d (g:G d),T d g) p
	d (g:ctxSubst xg p d) := F d (xc_f' (xgSubst xg p) d g).
Implicit Arguments elSubst [D GL P l G T].

Definition atSubstLt D (GL:Ctx D) P l G n T (xg:ExtCtx (extCtx GL P) l G) (a:AtCtx G n T) (Ho:n < l) p :
AtCtx (ctxSubst xg p) n (elSubst xg T p).
	revert l Ho xg.
	induction a;intro;(destruct l;intro;[exact (match lt_n_O _ Ho with end) |]);intro.

	apply (extSCtxInv_ext xg).
	clear xg.
	intro.
	unfold ctxSubst.
	simpl.
	apply topCtx.

	revert T a IHa.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	change (AtCtx (extCtx (ctxSubst xg p) (elSubst xg T' p)) (S n) (fun d g=>elSubst xg T p d (projT1 g))).
	apply popCtx.
	exact (IHa _ (lt_S_n _ _ Ho) xg).
Defined.
Implicit Arguments atSubstLt [D GL P l G n T].

Definition atSubstGt D (GL:Ctx D) P l G n T (xg:ExtCtx (extCtx GL P) l G) (a:AtCtx G (S n) T) (Ho:l <= n) p :
AtCtx (ctxSubst xg p) n (elSubst xg T p).
	revert n Ho T a.
	induction xg as [| l ? ? ? T'].

	intros.
	revert p.
	apply (popCtxInv_ext a (fun _ _ _ _ _=>_)).
	clear T a.
	intros.
	exact (atCtxEta a).

	intro.
	destruct n.
		intro.
		exact (match le_Sn_O _ Ho with end).
	intros.
	revert xg IHxg.
	apply (popCtxInv_ext a (fun _ _ _ _ _=>_)).
	clear T a.
	intros.
	change (AtCtx (extCtx (ctxSubst xg p) (elSubst xg T' p)) (S n) (fun d g=>elSubst xg T p d (projT1 g))).
	apply popCtx.
	exact (IHxg _ (le_S_n _ _ Ho) _ a).
Defined.
Implicit Arguments atSubstGt [D GL P l G n T].

Definition elMBumpG D (GL:Ctx D) P n G P' (xg:ExtCtx (extCtx GL P) n G) (a:AtCtx G n P')
(p:forall d g,P d g) : forall d g,P' d g.
	revert P' a.
	induction xg;intros ? ?.

	apply (topCtxInv_ext a (fun _ _ _ _ _=>_)).
	intros.
	apply p.

	apply (popCtxInv_ext a (fun _ _ _ _ _=>_)).
	clear P' a.
	intros P' ? ? ?.
	exact (IHxg _ a _ _).
Defined.
Implicit Arguments elMBumpG [D GL P n G P'].

Lemma ctxProj_SubstLt D (GL:Ctx D) P l G n T (xg:ExtCtx (extCtx GL P) l G) (a:AtCtx G n T) (Ho:n < l) p :
ctxProj (atSubstLt xg a Ho p) = elSubst xg (ctxProj a) p.
	revert l Ho xg.
	induction a;intro;(destruct l;intro;[exact (match lt_n_O _ Ho with end) |]);intro.

	revert Ho.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	simpl.
	rewrite extSCtxInv_extEq.
	reflexivity.

	revert T a IHa Ho.
	apply (extSCtxInv_ext xg).
	clear xg.
	intros.
	simpl.
	rewrite extSCtxInv_extEq.
	change (ctxProj (popCtx (atSubstLt xg a (lt_S_n _ _ Ho) p) (elSubst xg T' p)) =
		elSubst (extSCtx xg T') (ctxProj (popCtx a T')) p).
	simpl.
	rewrite IHa.
	reflexivity.
Qed.

Lemma ctxProj_SubstGt D (GL:Ctx D) P l G n T (xg:ExtCtx (extCtx GL P) l G) (a:AtCtx G (S n) T) (Ho:l <= n) p :
ctxProj (atSubstGt xg a Ho p) = elSubst xg (ctxProj a) p.
	revert n Ho T a.
	induction xg as [| l ? ? ? T'].

	intros.
	assert (nz : IsS (S n)).
		exact I.
	revert nz Ho p.
	apply (popCtxInv_ext a (fun GL P Sn T a=>forall (nz:IsS Sn) Ho p,
		ctxProj (atSubstGt (extOCtx _) (tr (fun n=>AtCtx (extCtx GL P) n T) (SUnfold nz) a) Ho p) =
		elSubst (extOCtx _) (ctxProj a) p)).
	simpl pred.
	simpl tr.
	clear T a.
	intros ? ? _ ? ?.
	simpl.
	rewrite popCtxInv_extEq.
	apply eq_trans with (1 := ctxProj_Eta _ _ _ _ a).
	reflexivity.

	intro.
	destruct n.
		intro.
		exact (match le_Sn_O _ Ho with end).
	intros.
	assert (nz : IsS (S (S n))).
		exact I.
	revert nz Ho p xg IHxg.
	apply (popCtxInv_ext a (fun G T' SSn T a=>forall (nz:IsS SSn) Ho p xg IHxg,
		ctxProj (atSubstGt (extSCtx xg T') (tr (fun n=>AtCtx (extCtx G T') n T) (SUnfold nz) a) Ho p) =
		elSubst (extSCtx xg T') (ctxProj a) p)).
	simpl pred.
	simpl tr.
	clear T a.
	intros ? ? _.
	intros.
	simpl.
	rewrite popCtxInv_extEq.
	change (ctxProj (popCtx (atSubstGt xg a (le_S_n _ _ Ho) p) (elSubst xg T' p)) =
		elSubst (extSCtx xg T') (ctxProj (popCtx a T')) p).
	simpl.
	rewrite IHxg.
	reflexivity.
Qed.

Lemma ctxProj_SubstEq D (GL:Ctx D) P n G P' (xg:ExtCtx (extCtx GL P) n G) (a:AtCtx G n P') p :
elSubst xg (elMBumpG xg a p) p = elSubst xg (ctxProj a) p.
	apply extAtCtxInd with (xg := xg) (a := a);clear n G P' xg a;intros;simpl.

	rewrite topCtxInv_extEq.
	reflexivity.

	rewrite popCtxInv_extEq.
	change ((fun d (g:ctxSubst (extSCtx xg T) p d)=>elSubst xg (elMBumpG xg a p) p d (projT1 g)) =
		(fun d g=>elSubst xg (ctxProj a) p d (projT1 g))).
	rewrite H.
	reflexivity.
Qed.

(* Stuff for substituting one variable for another. Probably should've called it atMBumpG. *)

Inductive AtCtxExt D (G:Ctx D) n' : Type := mkAtCtxExt T (a:AtCtx G n' T).
Implicit Arguments AtCtxExt [D].
Implicit Arguments mkAtCtxExt [D G n' T].

Definition ax_T D (G:Ctx D) n' (ax:AtCtxExt G n') := match ax with mkAtCtxExt T _ => T end.
Implicit Arguments ax_T [D G n'].

Definition ax_a D (G:Ctx D) n' (ax:AtCtxExt G n') : AtCtx G n' (ax_T ax) := match ax with mkAtCtxExt _ a => a end.
Implicit Arguments ax_a [D G n'].

Fixpoint atCtxExt D (GL:Ctx D) l G n T (xg:ExtCtx GL l G) (a:AtCtx GL n T) : AtCtxExt G (l + n) := match xg with
	extOCtx => mkAtCtxExt a |
	extSCtx _ _ xg T' => mkAtCtxExt (popCtx (ax_a (atCtxExt _ _ _ _ _ _ xg a)) T')
end.
Implicit Arguments atCtxExt [D GL l G n T].

Definition atCtxExtTEq D (GL:Ctx D) a b P G (b':AtCtx GL b P) (xg:ExtCtx (extCtx GL P) a G) :
forall P' (a':AtCtx G a P'),ax_T (atCtxExt xg (popCtx b' P)) = P'.
	induction xg as [| a];intros ? ?;simpl.

	apply (topCtxInv_ext a' (fun _ _ _ _ _=>_)).
	reflexivity.

	revert xg IHxg.
	apply (popCtxInv_ext a' (fun _ _ _ _ _=>_)).
	clear P' a'.
	intros P' a' ? ?.
	apply (tr (fun _=>_) (IHxg _ a')).
	reflexivity.
Defined.
Implicit Arguments atCtxExtTEq [D GL a b P G P'].

Lemma ctxProj_Ext D (GL:Ctx D) a b P G P' (b':AtCtx GL b P) (xg:ExtCtx (extCtx GL P) a G) (a':AtCtx G a P') :
ctxProj (tr (AtCtx G _) (atCtxExtTEq b' xg a') (ax_a (atCtxExt xg (popCtx b' P)))) = elMBumpG xg a' (ctxProj b').
	apply extAtCtxInd with (xg := xg) (a := a');clear a G P' xg a';[| intros a ? ? ? a' ? ?];simpl.

	rewrite topCtxInv_extEq.
	rewrite topCtxInv_extEq.
	reflexivity.

	rewrite popCtxInv_extEq.
	rewrite popCtxInv_extEq.
	rewrite <- H.
	rewrite <- (atCtxExtTEq b' xg a').
	reflexivity.
Qed.


Require Import Coq.Sets.Ensembles.
Require Import Coq.Lists.List.
Require Import Coq.micromega.Psatz.
Require Import Coq.Logic.ClassicalFacts.

Lemma prop_ext: prop_extensionality.
Proof.
  hnf; intros.
  set (A0 := fun x: unit => A).
  set (B0 := fun x: unit => B).
  assert (A0 = B0).
  + apply Extensionality_Ensembles.
    split; subst A0 B0; unfold Included, Ensembles.In; intros; tauto.
  + change A with (A0 tt).
    change B with (B0 tt).
    rewrite H0; auto.
Qed.

Lemma fin_subset_match {A B: Type} {P: A -> B -> Prop}: forall (X: Ensemble A) (Y: Ensemble B),
  (forall x, X x -> exists y, P x y /\ Y y) ->
  forall xs, Forall (fun x => X x) xs -> exists ys, Forall2 P xs ys /\ Forall (fun y => Y y) ys.
Proof.
  intros.
  induction xs as [| x0 xs].
  + exists nil; split; constructor.
  + inversion H0; subst.
    specialize (IHxs H4).
    destruct IHxs as [ys [? ?]].
    specialize (H x0 H3).
    destruct H as [y0 [? ?]].
    exists (y0 :: ys).
    split; constructor; auto.
Qed.

Lemma Forall2_lr_rev {A B: Type} {P: A -> B -> Prop}: forall xs ys,
  Forall2 (fun y x => P x y) ys xs ->
  Forall2 P xs ys.
Proof.
  intros.
  induction H; auto.
Qed.

(* This one copy from RamifyCoq *)
Lemma Forall_app_iff: forall {A : Type} (P : A -> Prop) (l1 l2 : list A), Forall P (l1 ++ l2) <-> Forall P l1 /\ Forall P l2.
Proof.
  intros; induction l1; intros.
  + simpl.
    assert (Forall P nil) by constructor; tauto.
  + simpl; split; intros.
    - inversion H; subst; split; try tauto.
      constructor; auto; tauto.
    - destruct H.
      inversion H; subst.
      constructor; auto; tauto.
Qed.

Inductive remove_rel {A: Type}: A -> list A -> list A -> Prop :=
| remove_rel_nil: forall a, remove_rel a nil nil
| remove_rel_cons_eq: forall a xs ys, remove_rel a xs ys -> remove_rel a (a :: xs) ys
| remove_rel_cons_neq: forall a b xs ys, a <> b -> remove_rel a xs ys -> remove_rel a (b :: xs) (b :: ys).

Lemma remove_rel_In: forall (A : Type) (l1 l2 : list A) (x : A), remove_rel x l1 l2 -> ~ In x l2.
Proof.
  intros.
  induction H.
  + intros [].
  + auto.
  + intros [|]; auto.
Qed.

Lemma remove_rel_exist: forall (A : Type) (l1 : list A) (x : A) (DEC: forall y, x = y \/ x <> y), exists l2, remove_rel x l1 l2.
Proof.
  intros.
  induction l1.
  + exists nil.
    apply remove_rel_nil.
  + destruct IHl1 as [l2 ?].
    destruct (DEC a).
    - exists l2; subst.
      apply remove_rel_cons_eq; auto.
    - exists (a :: l2); subst.
      apply remove_rel_cons_neq; auto.
Qed.

Lemma remove_rel_result_belong: forall (A : Type) (l1 l2 : list A) (x : A), remove_rel x l1 l2 -> Forall (fun y => In y l1) l2.
Proof.
  intros.
  induction H.
  + auto.
  + simpl.
    revert IHremove_rel; apply Forall_impl.
    intros; auto.
  + constructor; simpl; auto.
    revert IHremove_rel; apply Forall_impl.
    intros; auto.
Qed.

Definition isSome {A} (o: option A) := match o with Some _ => True | None => False end.

(* These three lemmas are copied from veric/assert_lemmas.v and veric/initial_world.v *)
Lemma nth_error_in_bounds: forall {A} (l: list A) i, (O <= i < length l)%nat
  -> exists x, nth_error l i = value x.
Proof.
intros until i; intros H.
revert i l H.
induction i; destruct l; intros; simpl in *;
  try solve [eauto | lia].
apply IHi; lia.
Qed.

Lemma nth_error_app: forall {T} (al bl : list T) (j: nat),
     nth_error (al++bl) (length al + j) = nth_error bl j.
Proof.
 intros. induction al; simpl; auto.
Qed.

Lemma nth_error_app1: forall {T} (al bl : list T) (j: nat),
     (j < length al)%nat ->
     nth_error (al++bl) j = nth_error al j.
Proof.
  intros. revert al H; induction j; destruct al; simpl; intros; auto; try lia.
   apply IHj. lia.
Qed.

Lemma nth_error_None_iff: forall {A} (l: list A) n, nth_error l n = None <-> n >= length l.
Proof.
  intros.
  revert n; induction l; intros; destruct n; simpl.
  + split; [intros _; lia | auto].
  + split; [intros _; lia | auto].
  + split; [intros; inversion H | lia].
  + rewrite IHl.
    lia.
Qed.

Lemma Forall_rev: forall {A} (P: A -> Prop) (l: list A), Forall P (rev l) <-> Forall P l.
Proof.
  intros.
  rewrite !Forall_forall.
  pose proof in_rev l.
  firstorder.
Qed.


From S5 Require Export inference.

Lemma ax_s5_subset (F G : form_set) (f : form) :
  ax_s5 F f -> subset F G -> ax_s5 G f.
Proof.
  intros H1 H2. induction H1.
  - apply a_0, H2, H.
  - apply a_1.
  - apply a_2.
  - apply a_3.
  - apply a_k.
  - apply a_t.
  - apply a_4.
  - apply a_b.
  - eapply mp.
    + apply IHax_s5_1, H2.
    + apply IHax_s5_2, H2.
  - apply nec. assumption.
Qed.

Lemma deduction_theorem_1 (G : form_set) (f g : form) :
  ax_s5 G (Impl f g) -> ax_s5 (add_singleton G f) g.
Proof.
  intros H0. eapply mp.
  - eapply ax_s5_subset.
    + apply H0.
    + apply subset_add_singleton.
  - apply a_0, member_add_singleton.
Qed.

Lemma deduction_theorem_2 (G : form_set) (f g : form) :
  ax_s5 (add_singleton G f) g -> ax_s5 G (Impl f g).
Proof.
  intros H. remember (add_singleton G f) as G'. induction H; subst.
  - destruct H.
    + rewrite H. apply ax_s5_self_impl.
    + eapply mp. apply a_1. apply a_0, H.
  - eapply mp. apply a_1. apply a_1.
  - eapply mp. apply a_1. apply a_2.
  - eapply mp. apply a_1. apply a_3.
  - eapply mp. apply a_1. apply a_k.
  - eapply mp. apply a_1. apply a_t.
  - eapply mp. apply a_1. apply a_4.
  - eapply mp. apply a_1. apply a_b.
  - eapply mp.
    + eapply mp.
      * apply a_2.
      * apply IHax_s5_1. reflexivity.
    + apply IHax_s5_2. reflexivity.
  - eapply mp. apply a_1. apply nec, H.
Qed.

Lemma deduction_theorem (G : form_set) (f g : form) :
  ax_s5 G (Impl f g) <-> ax_s5 (add_singleton G f) g.
Proof.
  split.
  - apply deduction_theorem_1.
  - apply deduction_theorem_2.
Qed.


(* Copyright (c) 2006, 2011-2012, 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 Arith List.

Require Import CpdtTactics Coinductive.

Set Implicit Arguments.
(* end hide *)

(** %\chapter{General Recursion}% *)

(** Termination of all programs is a crucial property of Gallina.  Non-terminating programs introduce logical inconsistency, where any theorem can be proved with an infinite loop.  Coq uses a small set of conservative, syntactic criteria to check termination of all recursive definitions.  These criteria are insufficient to support the natural encodings of a variety of important programming idioms.  Further, since Coq makes it so convenient to encode mathematics computationally, with functional programs, we may find ourselves wanting to employ more complicated recursion in mathematical definitions.

   What exactly are the conservative criteria that we run up against?  For _recursive_ definitions, recursive calls are only allowed on _syntactic subterms_ of the original primary argument, a restriction known as%\index{primitive recursion}% _primitive recursion_.  In fact, Coq's handling of reflexive inductive types (those defined in terms of functions returning the same type) gives a bit more flexibility than in traditional primitive recursion, but the term is still applied commonly.  In Chapter 5, we saw how _co-recursive_ definitions are checked against a syntactic guardedness condition that guarantees productivity.

   Many natural recursion patterns satisfy neither condition.  For instance, there is our simple running example in this chapter, merge sort.  We will study three different approaches to more flexible recursion, and the latter two of the approaches will even support definitions that may fail to terminate on certain inputs, without any up-front characterization of which inputs those may be.

   Before proceeding, it is important to note that the problem here is not as fundamental as it may appear.  The final example of Chapter 5 demonstrated what is called a%\index{deep embedding}% _deep embedding_ of the syntax and semantics of a programming language.  That is, we gave a mathematical definition of a language of programs and their meanings.  This language clearly admitted non-termination, and we could think of writing all our sophisticated recursive functions with such explicit syntax types.  However, in doing so, we forfeit our chance to take advantage of Coq's very good built-in support for reasoning about Gallina programs.  We would rather use a%\index{shallow embedding}% _shallow embedding_, where we model informal constructs by encoding them as normal Gallina programs.  Each of the three techniques of this chapter follows that style. *)

(** * Well-Founded Recursion *)

(** The essence of terminating recursion is that there are no infinite chains of nested recursive calls.  This intuition is commonly mapped to the mathematical idea of a%\index{well-founded relation}% _well-founded relation_, and the associated standard technique in Coq is%\index{well-founded recursion}% _well-founded recursion_.  The syntactic-subterm relation that Coq applies by default is well-founded, but many cases demand alternate well-founded relations.  To demonstrate, let us see where we get stuck on attempting a standard merge sort implementation. *)

Section mergeSort.
  Variable A : Type.
  Variable le : A -> A -> bool.

  (** We have a set equipped with some "less-than-or-equal-to" test. *)

  (** A standard function inserts an element into a sorted list, preserving sortedness. *)

  Fixpoint insert (x : A) (ls : list A) : list A :=
    match ls with
      | nil => x :: nil
      | h :: ls' =>
	if le x h
	  then x :: ls
	  else h :: insert x ls'
    end.

  (** We will also need a function to merge two sorted lists.  (We use a less efficient implementation than usual, because the more efficient implementation already forces us to think about well-founded recursion, while here we are only interested in setting up the example of merge sort.) *)

  Fixpoint merge (ls1 ls2 : list A) : list A :=
    match ls1 with
      | nil => ls2
      | h :: ls' => insert h (merge ls' ls2)
    end.

  (** The last helper function for classic merge sort is the one that follows, to split a list arbitrarily into two pieces of approximately equal length. *)

  Fixpoint split (ls : list A) : list A * list A :=
    match ls with
      | nil => (nil, nil)
      | h :: nil => (h :: nil, nil)
      | h1 :: h2 :: ls' =>
	let (ls1, ls2) := split ls' in
	  (h1 :: ls1, h2 :: ls2)
    end.

  (** Now, let us try to write the final sorting function, using a natural number "[<=]" test [leb] from the standard library.
[[
  Fixpoint mergeSort (ls : list A) : list A :=
    if leb (length ls) 1
      then ls
      else let lss := split ls in
	merge (mergeSort (fst lss)) (mergeSort (snd lss)).
]]

<<
Recursive call to mergeSort has principal argument equal to
"fst (split ls)" instead of a subterm of "ls".
>>

The definition is rejected for not following the simple primitive recursion criterion.  In particular, it is not apparent that recursive calls to [mergeSort] are syntactic subterms of the original argument [ls]; indeed, they are not, yet we know this is a well-founded recursive definition.

To produce an acceptable definition, we need to choose a well-founded relation and prove that [mergeSort] respects it.  A good starting point is an examination of how well-foundedness is formalized in the Coq standard library. *)

  Print well_founded.
  (** %\vspace{-.15in}% [[
well_founded =
fun (A : Type) (R : A -> A -> Prop) => forall a : A, Acc R a
]]

The bulk of the definitional work devolves to the%\index{accessibility relation}\index{Gallina terms!Acc}% _accessibility_ relation [Acc], whose definition we may also examine. *)

(* begin hide *)
(* begin thide *)
Definition Acc_intro' := Acc_intro.
(* end thide *)
(* end hide *)

  Print Acc.
(** %\vspace{-.15in}% [[
Inductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=
    Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x
]]

In prose, an element [x] is accessible for a relation [R] if every element "less than" [x] according to [R] is also accessible.  Since [Acc] is defined inductively, we know that any accessibility proof involves a finite chain of invocations, in a certain sense that we can make formal.  Building on Chapter 5's examples, let us define a co-inductive relation that is closer to the usual informal notion of "absence of infinite decreasing chains." *)

  CoInductive infiniteDecreasingChain A (R : A -> A -> Prop) : stream A -> Prop :=
  | ChainCons : forall x y s, infiniteDecreasingChain R (Cons y s)
    -> R y x
    -> infiniteDecreasingChain R (Cons x (Cons y s)).

(** We can now prove that any accessible element cannot be the beginning of any infinite decreasing chain. *)

(* begin thide *)
  Lemma noBadChains' : forall A (R : A -> A -> Prop) x, Acc R x
    -> forall s, ~infiniteDecreasingChain R (Cons x s).
    induction 1; crush;
      match goal with
        | [ H : infiniteDecreasingChain _ _ |- _ ] => inversion H; eauto
      end.
  Qed.

(** From here, the absence of infinite decreasing chains in well-founded sets is immediate. *)

  Theorem noBadChains : forall A (R : A -> A -> Prop), well_founded R
    -> forall s, ~infiniteDecreasingChain R s.
    destruct s; apply noBadChains'; auto.
  Qed.
(* end thide *)

(** Absence of infinite decreasing chains implies absence of infinitely nested recursive calls, for any recursive definition that respects the well-founded relation.  The [Fix] combinator from the standard library formalizes that intuition: *)

  Check Fix.
(** %\vspace{-.15in}%[[
Fix
     : forall (A : Type) (R : A -> A -> Prop),
       well_founded R ->
       forall P : A -> Type,
       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
       forall x : A, P x
]]

A call to %\index{Gallina terms!Fix}%[Fix] must present a relation [R] and a proof of its well-foundedness.  The next argument, [P], is the possibly dependent range type of the function we build; the domain [A] of [R] is the function's domain.  The following argument has this type:
[[
       forall x : A, (forall y : A, R y x -> P y) -> P x
]]

This is an encoding of the function body.  The input [x] stands for the function argument, and the next input stands for the function we are defining.  Recursive calls are encoded as calls to the second argument, whose type tells us it expects a value [y] and a proof that [y] is "less than" [x], according to [R].  In this way, we enforce the well-foundedness restriction on recursive calls.

The rest of [Fix]'s type tells us that it returns a function of exactly the type we expect, so we are now ready to use it to implement [mergeSort].  Careful readers may have noticed that [Fix] has a dependent type of the sort we met in the previous chapter.

Before writing [mergeSort], we need to settle on a well-founded relation.  The right one for this example is based on lengths of lists. *)

  Definition lengthOrder (ls1 ls2 : list A) :=
    length ls1 < length ls2.

  (** We must prove that the relation is truly well-founded.  To save some space in the rest of this chapter, we skip right to nice, automated proof scripts, though we postpone introducing the principles behind such scripts to Part III of the book.  Curious readers may still replace semicolons with periods and newlines to step through these scripts interactively. *)

  Hint Constructors Acc.

  Lemma lengthOrder_wf' : forall len, forall ls, length ls <= len -> Acc lengthOrder ls.
    unfold lengthOrder; induction len; crush.
  Defined.

  Theorem lengthOrder_wf : well_founded lengthOrder.
    red; intro; eapply lengthOrder_wf'; eauto.
  Defined.

  (** Notice that we end these proofs with %\index{Vernacular commands!Defined}%[Defined], not [Qed].  Recall that [Defined] marks the theorems as %\emph{%#<i>#transparent#</i>#%}%, so that the details of their proofs may be used during program execution.  Why could such details possibly matter for computation?  It turns out that [Fix] satisfies the primitive recursion restriction by declaring itself as _recursive in the structure of [Acc] proofs_.  This is possible because [Acc] proofs follow a predictable inductive structure.  We must do work, as in the last theorem's proof, to establish that all elements of a type belong to [Acc], but the automatic unwinding of those proofs during recursion is straightforward.  If we ended the proof with [Qed], the proof details would be hidden from computation, in which case the unwinding process would get stuck.

     To justify our two recursive [mergeSort] calls, we will also need to prove that [split] respects the [lengthOrder] relation.  These proofs, too, must be kept transparent, to avoid stuckness of [Fix] evaluation.  We use the syntax [@foo] to reference identifier [foo] with its implicit argument behavior turned off.  (The proof details below use Ltac features not introduced yet, and they are safe to skip for now.) *)

  Lemma split_wf : forall len ls, 2 <= length ls <= len
    -> let (ls1, ls2) := split ls in
      lengthOrder ls1 ls /\ lengthOrder ls2 ls.
    unfold lengthOrder; induction len; crush; do 2 (destruct ls; crush);
      destruct (le_lt_dec 2 (length ls));
        repeat (match goal with
                  | [ _ : length ?E < 2 |- _ ] => destruct E
                  | [ _ : S (length ?E) < 2 |- _ ] => destruct E
                  | [ IH : _ |- context[split ?L] ] =>
                    specialize (IH L); destruct (split L); destruct IH
                end; crush).
  Defined.

  Ltac split_wf := intros ls ?; intros; generalize (@split_wf (length ls) ls);
    destruct (split ls); destruct 1; crush.

  Lemma split_wf1 : forall ls, 2 <= length ls
    -> lengthOrder (fst (split ls)) ls.
    split_wf.
  Defined.

  Lemma split_wf2 : forall ls, 2 <= length ls
    -> lengthOrder (snd (split ls)) ls.
    split_wf.
  Defined.

  Hint Resolve split_wf1 split_wf2.

  (** To write the function definition itself, we use the %\index{tactics!refine}%[refine] tactic as a convenient way to write a program that needs to manipulate proofs, without writing out those proofs manually.  We also use a replacement [le_lt_dec] for [leb] that has a more interesting dependent type.  (Note that we would not be able to complete the definition without this change, since [refine] will generate subgoals for the [if] branches based only on the _type_ of the test expression, not its _value_.) *)

  Definition mergeSort : list A -> list A.
(* begin thide *)
    refine (Fix lengthOrder_wf (fun _ => list A)
      (fun (ls : list A)
        (mergeSort : forall ls' : list A, lengthOrder ls' ls -> list A) =>
        if le_lt_dec 2 (length ls)
	  then let lss := split ls in
            merge (mergeSort (fst lss) _) (mergeSort (snd lss) _)
	  else ls)); subst lss; eauto.
  Defined.
(* end thide *)
End mergeSort.

(** The important thing is that it is now easy to evaluate calls to [mergeSort]. *)

Eval compute in mergeSort leb (1 :: 2 :: 36 :: 8 :: 19 :: nil).
(** [= 1 :: 2 :: 8 :: 19 :: 36 :: nil] *)

(** %\smallskip{}%Since the subject of this chapter is merely how to define functions with unusual recursion structure, we will not prove any further correctness theorems about [mergeSort]. Instead, we stop at proving that [mergeSort] has the expected computational behavior, for all inputs, not merely the one we just tested. *)

(* begin thide *)
Theorem mergeSort_eq : forall A (le : A -> A -> bool) ls,
  mergeSort le ls = if le_lt_dec 2 (length ls)
    then let lss := split ls in
      merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
    else ls.
  intros; apply (Fix_eq (@lengthOrder_wf A) (fun _ => list A)); intros.

  (** The library theorem [Fix_eq] imposes one more strange subgoal upon us.  We must prove that the function body is unable to distinguish between "self" arguments that map equal inputs to equal outputs.  One might think this should be true of any Gallina code, but in fact this general%\index{extensionality}% _function extensionality_ property is neither provable nor disprovable within Coq.  The type of [Fix_eq] makes clear what we must show manually: *)

  Check Fix_eq.
(** %\vspace{-.15in}%[[
Fix_eq
     : forall (A : Type) (R : A -> A -> Prop) (Rwf : well_founded R)
         (P : A -> Type)
         (F : forall x : A, (forall y : A, R y x -> P y) -> P x),
       (forall (x : A) (f g : forall y : A, R y x -> P y),
        (forall (y : A) (p : R y x), f y p = g y p) -> F x f = F x g) ->
       forall x : A,
       Fix Rwf P F x = F x (fun (y : A) (_ : R y x) => Fix Rwf P F y)
]]

  Most such obligations are dischargeable with straightforward proof automation, and this example is no exception. *)

  match goal with
    | [ |- context[match ?E with left _ => _ | right _ => _ end] ] => destruct E
  end; simpl; f_equal; auto.
Qed.
(* end thide *)

(** As a final test of our definition's suitability, we can extract to OCaml. *)

Extraction mergeSort.

(** <<
let rec mergeSort le x =
  match le_lt_dec (S (S O)) (length x) with
  | Left ->
    let lss = split x in
    merge le (mergeSort le (fst lss)) (mergeSort le (snd lss))
  | Right -> x
>>

  We see almost precisely the same definition we would have written manually in OCaml!  It might be a good exercise for the reader to use the commands we saw in the previous chapter to clean up some remaining differences from idiomatic OCaml.

  One more piece of the full picture is missing.  To go on and prove correctness of [mergeSort], we would need more than a way of unfolding its definition.  We also need an appropriate induction principle matched to the well-founded relation.  Such a principle is available in the standard library, though we will say no more about its details here. *)

Check well_founded_induction.
(** %\vspace{-.15in}%[[
well_founded_induction
     : forall (A : Type) (R : A -> A -> Prop),
       well_founded R ->
       forall P : A -> Set,
       (forall x : A, (forall y : A, R y x -> P y) -> P x) ->
       forall a : A, P a
]]

  Some more recent Coq features provide more convenient syntax for defining recursive functions.  Interested readers can consult the Coq manual about the commands %\index{Function}%[Function] and %\index{Program Fixpoint}%[Program Fixpoint]. *)

(** * A Non-Termination Monad Inspired by Domain Theory *)

(** The key insights of %\index{domain theory}%domain theory%~\cite{WinskelDomains}% inspire the next approach to modeling non-termination.  Domain theory is based on _information orders_ that relate values representing computation results, according to how much information these values convey.  For instance, a simple domain might include values "the program does not terminate" and "the program terminates with the answer 5."  The former is considered to be an _approximation_ of the latter, while the latter is _not_ an approximation of "the program terminates with the answer 6."  The details of domain theory will not be important in what follows; we merely borrow the notion of an approximation ordering on computation results.

   Consider this definition of a type of computations. *)

Section computation.
  Variable A : Type.
  (** The type [A] describes the result a computation will yield, if it terminates.

     We give a rich dependent type to computations themselves: *)

  Definition computation :=
    {f : nat -> option A
      | forall (n : nat) (v : A),
	f n = Some v
	-> forall (n' : nat), n' >= n
	  -> f n' = Some v}.

  (** A computation is fundamentally a function [f] from an _approximation level_ [n] to an optional result.  Intuitively, higher [n] values enable termination in more cases than lower values.  A call to [f] may return [None] to indicate that [n] was not high enough to run the computation to completion; higher [n] values may yield [Some].  Further, the proof obligation within the subset type asserts that [f] is _monotone_ in an appropriate sense: when some [n] is sufficient to produce termination, so are all higher [n] values, and they all yield the same program result [v].

  It is easy to define a relation characterizing when a computation runs to a particular result at a particular approximation level. *)

  Definition runTo (m : computation) (n : nat) (v : A) :=
    proj1_sig m n = Some v.

  (** On top of [runTo], we also define [run], which is the most abstract notion of when a computation runs to a value. *)

  Definition run (m : computation) (v : A) :=
    exists n, runTo m n v.
End computation.

(** The book source code contains at this point some tactics, lemma proofs, and hint commands, to be used in proving facts about computations.  Since their details are orthogonal to the message of this chapter, I have omitted them in the rendered version. *)
(* begin hide *)

Hint Unfold runTo.

Ltac run' := unfold run, runTo in *; try red; crush;
  repeat (match goal with
            | [ _ : proj1_sig ?E _ = _ |- _ ] =>
              match goal with
                | [ x : _ |- _ ] =>
                  match x with
                    | E => destruct E
                  end
              end
            | [ |- context[match ?M with exist _ _ => _ end] ] => let Heq := fresh "Heq" in
              case_eq M; intros ? ? Heq; try rewrite Heq in *; try subst
            | [ _ : context[match ?M with exist _ _ => _ end] |- _ ] => let Heq := fresh "Heq" in
              case_eq M; intros ? ? Heq; try rewrite Heq in *; subst
            | [ H : forall n v, ?E n = Some v -> _,
                _ : context[match ?E ?N with Some _ => _ | None => _ end] |- _ ] =>
              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate
            | [ H : forall n v, ?E n = Some v -> _, H' : ?E _ = Some _ |- _ ] => rewrite (H _ _ H') by auto
          end; simpl in *); eauto 7.

Ltac run := run'; repeat (match goal with
                            | [ H : forall n v, ?E n = Some v -> _
                                |- context[match ?E ?N with Some _ => _ | None => _ end] ] =>
                              specialize (H N); destruct (E N); try rewrite (H _ (eq_refl _)) by auto; try discriminate
                          end; run').

Lemma ex_irrelevant : forall P : Prop, P -> exists n : nat, P.
  exists 0; auto.
Qed.

Hint Resolve ex_irrelevant.

Require Import Max.

Theorem max_spec_le : forall n m, n <= m /\ max n m = m \/ m <= n /\ max n m = n.
  induction n; destruct m; simpl; intuition;
    specialize (IHn m); intuition.
Qed.

Ltac max := intros n m; generalize (max_spec_le n m); crush.

Lemma max_1 : forall n m, max n m >= n.
  max.
Qed.

Lemma max_2 : forall n m, max n m >= m.
  max.
Qed.

Hint Resolve max_1 max_2.

Lemma ge_refl : forall n, n >= n.
  crush.
Qed.

Hint Resolve ge_refl.

Hint Extern 1 => match goal with
                   | [ H : _ = exist _ _ _ |- _ ] => rewrite H
                 end.
(* end hide *)
(** remove printing exists *)

(** Now, as a simple first example of a computation, we can define [Bottom], which corresponds to an infinite loop.  For any approximation level, it fails to terminate (returns [None]).  Note the use of [abstract] to create a new opaque lemma for the proof found by the #<tt>#%\coqdocvar{%run%}%#</tt># tactic.  In contrast to the previous section, opaque proofs are fine here, since the proof components of computations do not influence evaluation behavior.  It is generally preferable to make proofs opaque when possible, as this enforces a kind of modularity in the code to follow, preventing it from depending on any details of the proof. *)

Section Bottom.
  Variable A : Type.

  Definition Bottom : computation A.
    exists (fun _ : nat => @None A); abstract run.
  Defined.

  Theorem run_Bottom : forall v, ~run Bottom v.
    run.
  Qed.
End Bottom.

(** A slightly more complicated example is [Return], which gives the same terminating answer at every approximation level. *)

Section Return.
  Variable A : Type.
  Variable v : A.

  Definition Return : computation A.
    intros; exists (fun _ : nat => Some v); abstract run.
  Defined.

  Theorem run_Return : run Return v.
    run.
  Qed.
End Return.

(** The name [Return] was meant to be suggestive of the standard operations of %\index{monad}%monads%~\cite{Monads}%.  The other standard operation is [Bind], which lets us run one computation and, if it terminates, pass its result off to another computation.  We implement bind using the notation [let (x, y) := e1 in e2], for pulling apart the value [e1] which may be thought of as a pair.  The second component of a [computation] is a proof, which we do not need to mention directly in the definition of [Bind]. *)

Section Bind.
  Variables A B : Type.
  Variable m1 : computation A.
  Variable m2 : A -> computation B.

  Definition Bind : computation B.
    exists (fun n =>
      let (f1, _) := m1 in
      match f1 n with
	| None => None
	| Some v =>
	  let (f2, _) := m2 v in
	    f2 n
      end); abstract run.
  Defined.

  Theorem run_Bind : forall (v1 : A) (v2 : B),
    run m1 v1
    -> run (m2 v1) v2
    -> run Bind v2.
    run; match goal with
           | [ x : nat, y : nat |- _ ] => exists (max x y)
         end; run.
  Qed.
End Bind.

(** A simple notation lets us write [Bind] calls the way they appear in Haskell. *)

Notation "x <- m1 ; m2" :=
  (Bind m1 (fun x => m2)) (right associativity, at level 70).

(** We can verify that we have indeed defined a monad, by proving the standard monad laws.  Part of the exercise is choosing an appropriate notion of equality between computations.  We use "equality at all approximation levels." *)

Definition meq A (m1 m2 : computation A) := forall n, proj1_sig m1 n = proj1_sig m2 n.

Theorem left_identity : forall A B (a : A) (f : A -> computation B),
  meq (Bind (Return a) f) (f a).
  run.
Qed.

Theorem right_identity : forall A (m : computation A),
  meq (Bind m (@Return _)) m.
  run.
Qed.

Theorem associativity : forall A B C (m : computation A)
  (f : A -> computation B) (g : B -> computation C),
  meq (Bind (Bind m f) g) (Bind m (fun x => Bind (f x) g)).
  run.
Qed.

(** Now we come to the piece most directly inspired by domain theory.  We want to support general recursive function definitions, but domain theory tells us that not all definitions are reasonable; some fail to be _continuous_ and thus represent unrealizable computations.  To formalize an analogous notion of continuity for our non-termination monad, we write down the approximation relation on computation results that we have had in mind all along. *)

Section lattice.
  Variable A : Type.

  Definition leq (x y : option A) :=
    forall v, x = Some v -> y = Some v.
End lattice.

(** We now have the tools we need to define a new [Fix] combinator that, unlike the one we saw in the prior section, does not require a termination proof, and in fact admits recursive definition of functions that fail to terminate on some or all inputs. *)

Section Fix.

  (** First, we have the function domain and range types. *)

  Variables A B : Type.

  (** Next comes the function body, which is written as though it can be parameterized over itself, for recursive calls. *)

  Variable f : (A -> computation B) -> (A -> computation B).

  (** Finally, we impose an obligation to prove that the body [f] is continuous.  That is, when [f] terminates according to one recursive version of itself, it also terminates with the same result at the same approximation level when passed a recursive version that refines the original, according to [leq]. *)

  Hypothesis f_continuous : forall n v v1 x,
    runTo (f v1 x) n v
    -> forall (v2 : A -> computation B),
      (forall x, leq (proj1_sig (v1 x) n) (proj1_sig (v2 x) n))
      -> runTo (f v2 x) n v.

  (** The computational part of the [Fix] combinator is easy to define.  At approximation level 0, we diverge; at higher levels, we run the body with a functional argument drawn from the next lower level. *)

  Fixpoint Fix' (n : nat) (x : A) : computation B :=
    match n with
      | O => Bottom _
      | S n' => f (Fix' n') x
    end.

  (** Now it is straightforward to package [Fix'] as a computation combinator [Fix]. *)

  Hint Extern 1 (_ >= _) => omega.
  Hint Unfold leq.

  Lemma Fix'_ok : forall steps n x v, proj1_sig (Fix' n x) steps = Some v
    -> forall n', n' >= n
      -> proj1_sig (Fix' n' x) steps = Some v.
    unfold runTo in *; induction n; crush;
      match goal with
        | [ H : _ >= _ |- _ ] => inversion H; crush; eauto
      end.
  Qed.

  Hint Resolve Fix'_ok.

  Hint Extern 1 (proj1_sig _ _ = _) => simpl;
    match goal with
      | [ |- proj1_sig ?E _ = _ ] => eapply (proj2_sig E)
    end.

  Definition Fix : A -> computation B.
    intro x; exists (fun n => proj1_sig (Fix' n x) n); abstract run.
  Defined.

  (** Finally, we can prove that [Fix] obeys the expected computation rule. *)

  Theorem run_Fix : forall x v,
    run (f Fix x) v
    -> run (Fix x) v.
    run; match goal with
           | [ n : nat |- _ ] => exists (S n); eauto
         end.
  Qed.
End Fix.

(* begin hide *)
Lemma leq_Some : forall A (x y : A), leq (Some x) (Some y)
  -> x = y.
  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.
Qed.

Lemma leq_None : forall A (x y : A), leq (Some x) None
  -> False.
  intros ? ? ? H; generalize (H _ (eq_refl _)); crush.
Qed.

Ltac mergeSort' := run;
  repeat (match goal with
            | [ |- context[match ?E with O => _ | S _ => _ end] ] => destruct E
          end; run);
  repeat match goal with
           | [ H : forall x, leq (proj1_sig (?f x) _) (proj1_sig (?g x) _) |- _ ] =>
             match goal with
               | [ H1 : f ?arg = _, H2 : g ?arg = _ |- _ ] =>
                 generalize (H arg); rewrite H1; rewrite H2; clear H1 H2; simpl; intro
             end
         end; run; repeat match goal with
                            | [ H : _ |- _ ] => (apply leq_None in H; tauto) || (apply leq_Some in H; subst)
                          end; auto.
(* end hide *)

(** After all that work, it is now fairly painless to define a version of [mergeSort] that requires no proof of termination.  We appeal to a program-specific tactic whose definition is hidden here but present in the book source. *)

Definition mergeSort' : forall A, (A -> A -> bool) -> list A -> computation (list A).
  refine (fun A le => Fix
    (fun (mergeSort : list A -> computation (list A))
      (ls : list A) =>
      if le_lt_dec 2 (length ls)
	then let lss := split ls in
          ls1 <- mergeSort (fst lss);
          ls2 <- mergeSort (snd lss);
          Return (merge le ls1 ls2)
	else Return ls) _); abstract mergeSort'.
Defined.

(** Furthermore, "running" [mergeSort'] on concrete inputs is as easy as choosing a sufficiently high approximation level and letting Coq's computation rules do the rest.  Contrast this with the proof work that goes into deriving an evaluation fact for a deeply embedded language, with one explicit proof rule application per execution step. *)

Lemma test_mergeSort' : run (mergeSort' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))
  (1 :: 2 :: 8 :: 19 :: 36 :: nil).
  exists 4; reflexivity.
Qed.

(** There is another benefit of our new [Fix] compared with the one we used in the previous section: we can now write recursive functions that sometimes fail to terminate, without losing easy reasoning principles for the terminating cases.  Consider this simple example, which appeals to another tactic whose definition we elide here. *)

(* begin hide *)
Ltac looper := unfold leq in *; run;
  repeat match goal with
           | [ x : unit |- _ ] => destruct x
           | [ x : bool |- _ ] => destruct x
         end; auto.
(* end hide *)

Definition looper : bool -> computation unit.
  refine (Fix (fun looper (b : bool) =>
    if b then Return tt else looper b) _); abstract looper.
Defined.

Lemma test_looper : run (looper true) tt.
  exists 1; reflexivity.
Qed.

(** As before, proving outputs for specific inputs is as easy as demonstrating a high enough approximation level.

   There are other theorems that are important to prove about combinators like [Return], [Bind], and [Fix].  In general, for a computation [c], we sometimes have a hypothesis proving [run c v] for some [v], and we want to perform inversion to deduce what [v] must be.  Each combinator should ideally have a theorem of that kind, for [c] built directly from that combinator.  We have omitted such theorems here, but they are not hard to prove.  In general, the domain theory-inspired approach avoids the type-theoretic "gotchas" that tend to show up in approaches that try to mix normal Coq computation with explicit syntax types.  The next section of this chapter demonstrates two alternate approaches of that sort.  In the final section of the chapter, we review the pros and cons of the different choices, coming to the conclusion that none of them is obviously better than any one of the others for all situations. *)

(** * Co-Inductive Non-Termination Monads *)

(** There are two key downsides to both of the previous approaches: both require unusual syntax based on explicit calls to fixpoint combinators, and both generate immediate proof obligations about the bodies of recursive definitions.  In Chapter 5, we have already seen how co-inductive types support recursive definitions that exhibit certain well-behaved varieties of non-termination.  It turns out that we can leverage that co-induction support for encoding of general recursive definitions, by adding layers of co-inductive syntax.  In effect, we mix elements of shallow and deep embeddings.

   Our first example of this kind, proposed by Capretta%~\cite{Capretta}%, defines a silly-looking type of thunks; that is, computations that may be forced to yield results, if they terminate. *)

CoInductive thunk (A : Type) : Type :=
| Answer : A -> thunk A
| Think : thunk A -> thunk A.

(** A computation is either an immediate [Answer] or another computation wrapped inside [Think].  Since [thunk] is co-inductive, every [thunk] type is inhabited by an infinite nesting of [Think]s, standing for non-termination.  Terminating results are [Answer] wrapped inside some finite number of [Think]s.

   Why bother to write such a strange definition?  The definition of [thunk] is motivated by the ability it gives us to define a "bind" operation, similar to the one we defined in the previous section. *)

CoFixpoint TBind A B (m1 : thunk A) (m2 : A -> thunk B) : thunk B :=
  match m1 with
    | Answer x => m2 x
    | Think m1' => Think (TBind m1' m2)
  end.

(** Note that the definition would violate the co-recursion guardedness restriction if we left out the seemingly superfluous [Think] on the righthand side of the second [match] branch.

   We can prove that [Answer] and [TBind] form a monad for [thunk].  The proof is omitted here but present in the book source.  As usual for this sort of proof, a key element is choosing an appropriate notion of equality for [thunk]s. *)

(* begin hide *)
CoInductive thunk_eq A : thunk A -> thunk A -> Prop :=
| EqAnswer : forall x, thunk_eq (Answer x) (Answer x)
| EqThinkL : forall m1 m2, thunk_eq m1 m2 -> thunk_eq (Think m1) m2
| EqThinkR : forall m1 m2, thunk_eq m1 m2 -> thunk_eq m1 (Think m2).

Section thunk_eq_coind.
  Variable A : Type.
  Variable P : thunk A -> thunk A -> Prop.

  Hypothesis H : forall m1 m2, P m1 m2
    -> match m1, m2 with
         | Answer x1, Answer x2 => x1 = x2
         | Think m1', Think m2' => P m1' m2'
         | Think m1', _ => P m1' m2
         | _, Think m2' => P m1 m2'
       end.

  Theorem thunk_eq_coind : forall m1 m2, P m1 m2 -> thunk_eq m1 m2.
    cofix; intros;
      match goal with
        | [ H' : P _ _ |- _ ] => specialize (H H'); clear H'
      end; destruct m1; destruct m2; subst; repeat constructor; auto.
  Qed.
End thunk_eq_coind.
(* end hide *)

(** In the proofs to follow, we will need a function similar to one we saw in Chapter 5, to pull apart and reassemble a [thunk] in a way that provokes reduction of co-recursive calls. *)

Definition frob A (m : thunk A) : thunk A :=
  match m with
    | Answer x => Answer x
    | Think m' => Think m'
  end.

Theorem frob_eq : forall A (m : thunk A), frob m = m.
  destruct m; reflexivity.
Qed.

(* begin hide *)
Theorem thunk_eq_frob : forall A (m1 m2 : thunk A),
  thunk_eq (frob m1) (frob m2)
  -> thunk_eq m1 m2.
  intros; repeat rewrite frob_eq in *; auto.
Qed.

Ltac findDestr := match goal with
                    | [ |- context[match ?E with Answer _ => _ | Think _ => _ end] ] =>
                      match E with
                        | context[match _ with Answer _ => _ | Think _ => _ end] => fail 1
                        | _ => destruct E
                      end
                  end.

Theorem thunk_eq_refl : forall A (m : thunk A), thunk_eq m m.
  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = m2)); crush; findDestr; reflexivity.
Qed.

Hint Resolve thunk_eq_refl.

Theorem tleft_identity : forall A B (a : A) (f : A -> thunk B),
  thunk_eq (TBind (Answer a) f) (f a).
  intros; apply thunk_eq_frob; crush.
Qed.

Theorem tright_identity : forall A (m : thunk A),
  thunk_eq (TBind m (@Answer _)) m.
  intros; apply (thunk_eq_coind (fun m1 m2 => m1 = TBind m2 (@Answer _))); crush;
    findDestr; reflexivity.
Qed.

Lemma TBind_Answer : forall (A B : Type) (v : A) (m2 : A -> thunk B),
  TBind (Answer v) m2 = m2 v.
  intros; rewrite <- (frob_eq (TBind (Answer v) m2));
    simpl; findDestr; reflexivity.
Qed.

Hint Rewrite TBind_Answer.

(** printing exists $\exists$ *)

Theorem tassociativity : forall A B C (m : thunk A) (f : A -> thunk B) (g : B -> thunk C),
  thunk_eq (TBind (TBind m f) g) (TBind m (fun x => TBind (f x) g)).
  intros; apply (thunk_eq_coind (fun m1 m2 => (exists m,
    m1 = TBind (TBind m f) g
    /\ m2 = TBind m (fun x => TBind (f x) g))
  \/ m1 = m2)); crush; eauto; repeat (findDestr; crush; eauto).
Qed.
(* end hide *)

(** As a simple example, here is how we might define a tail-recursive factorial function. *)

CoFixpoint fact (n acc : nat) : thunk nat :=
  match n with
    | O => Answer acc
    | S n' => Think (fact n' (S n' * acc))
  end.

(** To test our definition, we need an evaluation relation that characterizes results of evaluating [thunk]s. *)

Inductive eval A : thunk A -> A -> Prop :=
| EvalAnswer : forall x, eval (Answer x) x
| EvalThink : forall m x, eval m x -> eval (Think m) x.

Hint Rewrite frob_eq.

Lemma eval_frob : forall A (c : thunk A) x,
  eval (frob c) x
  -> eval c x.
  crush.
Qed.

Theorem eval_fact : eval (fact 5 1) 120.
  repeat (apply eval_frob; simpl; constructor).
Qed.

(** We need to apply constructors of [eval] explicitly, but the process is easy to automate completely for concrete input programs.

   Now consider another very similar definition, this time of a Fibonacci number function. *)

Notation "x <- m1 ; m2" :=
  (TBind m1 (fun x => m2)) (right associativity, at level 70).

(* begin hide *)
(* begin thide *)
Definition fib := pred.
(* end thide *)
(* end hide *)

(** %\vspace{-.3in}%[[
CoFixpoint fib (n : nat) : thunk nat :=
  match n with
    | 0 => Answer 1
    | 1 => Answer 1
    | _ => n1 <- fib (pred n);
      n2 <- fib (pred (pred n));
      Answer (n1 + n2)
  end.
]]

Coq complains that the guardedness condition is violated.  The two recursive calls are immediate arguments to [TBind], but [TBind] is not a constructor of [thunk].  Rather, it is a defined function.  This example shows a very serious limitation of [thunk] for traditional functional programming: it is not, in general, possible to make recursive calls and then make further recursive calls, depending on the first call's result.  The [fact] example succeeded because it was already tail recursive, meaning no further computation is needed after a recursive call.

%\medskip%

I know no easy fix for this problem of [thunk], but we can define an alternate co-inductive monad that avoids the problem, based on a proposal by Megacz%~\cite{Megacz}%.  We ran into trouble because [TBind] was not a constructor of [thunk], so let us define a new type family where "bind" is a constructor. *)

CoInductive comp (A : Type) : Type :=
| Ret : A -> comp A
| Bnd : forall B, comp B -> (B -> comp A) -> comp A.

(** This example shows off Coq's support for%\index{recursively non-uniform parameters}% _recursively non-uniform parameters_, as in the case of the parameter [A] declared above, where each constructor's type ends in [comp A], but there is a recursive use of [comp] with a different parameter [B].  Beside that technical wrinkle, we see the simplest possible definition of a monad, via a type whose two constructors are precisely the monad operators.

   It is easy to define the semantics of terminating [comp] computations. *)

Inductive exec A : comp A -> A -> Prop :=
| ExecRet : forall x, exec (Ret x) x
| ExecBnd : forall B (c : comp B) (f : B -> comp A) x1 x2, exec (A := B) c x1
  -> exec (f x1) x2
  -> exec (Bnd c f) x2.

(** We can also prove that [Ret] and [Bnd] form a monad according to a notion of [comp] equality based on [exec], but we omit details here; they are in the book source at this point. *)

(* begin hide *)
Hint Constructors exec.

Definition comp_eq A (c1 c2 : comp A) := forall r, exec c1 r <-> exec c2 r.

Ltac inverter := repeat match goal with
                          | [ H : exec _ _ |- _ ] => inversion H; []; crush
                        end.

Theorem cleft_identity : forall A B (a : A) (f : A -> comp B),
  comp_eq (Bnd (Ret a) f) (f a).
  red; crush; inverter; eauto.
Qed.

Theorem cright_identity : forall A (m : comp A),
  comp_eq (Bnd m (@Ret _)) m.
  red; crush; inverter; eauto.
Qed.

Lemma cassociativity1 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,
  exec c r
  -> forall m, c = Bnd (Bnd m f) g
   -> exec (Bnd m (fun x => Bnd (f x) g)) r.
  induction 1; crush.
  match goal with
    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst
  end.
  move H3 after A.
  generalize dependent B0.
  do 2 intro.
  subst.
  crush.
  inversion H; clear H; crush.
  eauto.
Qed.

Lemma cassociativity2 : forall A B C (f : A -> comp B) (g : B -> comp C) r c,
  exec c r
  -> forall m, c = Bnd m (fun x => Bnd (f x) g)
   -> exec (Bnd (Bnd m f) g) r.
  induction 1; crush.
  match goal with
    | [ H : Bnd _ _ = Bnd _ _ |- _ ] => injection H; clear H; intros; try subst
  end.
  move H3 after B.
  generalize dependent B0.
  do 2 intro.
  subst.
  crush.
  inversion H0; clear H0; crush.
  eauto.
Qed.

Hint Resolve cassociativity1 cassociativity2.

Theorem cassociativity : forall A B C (m : comp A) (f : A -> comp B) (g : B -> comp C),
  comp_eq (Bnd (Bnd m f) g) (Bnd m (fun x => Bnd (f x) g)).
  red; crush; eauto.
Qed.
(* end hide *)

(** Not only can we define the Fibonacci function with the new monad, but even our running example of merge sort becomes definable.  By shadowing our previous notation for "bind," we can write almost exactly the same code as in our previous [mergeSort'] definition, but with less syntactic clutter. *)

Notation "x <- m1 ; m2" := (Bnd m1 (fun x => m2)).

CoFixpoint mergeSort'' A (le : A -> A -> bool) (ls : list A) : comp (list A) :=
  if le_lt_dec 2 (length ls)
    then let lss := split ls in
      ls1 <- mergeSort'' le (fst lss);
      ls2 <- mergeSort'' le (snd lss);
      Ret (merge le ls1 ls2)
    else Ret ls.

(** To execute this function, we go through the usual exercise of writing a function to catalyze evaluation of co-recursive calls. *)

Definition frob' A (c : comp A) :=
  match c with
    | Ret x => Ret x
    | Bnd _ c' f => Bnd c' f
  end.

Lemma exec_frob : forall A (c : comp A) x,
  exec (frob' c) x
  -> exec c x.
  destruct c; crush.
Qed.

(** Now the same sort of proof script that we applied for testing [thunk]s will get the job done. *)

Lemma test_mergeSort'' : exec (mergeSort'' leb (1 :: 2 :: 36 :: 8 :: 19 :: nil))
  (1 :: 2 :: 8 :: 19 :: 36 :: nil).
  repeat (apply exec_frob; simpl; econstructor).
Qed.

(** Have we finally reached the ideal solution for encoding general recursive definitions, with minimal hassle in syntax and proof obligations?  Unfortunately, we have not, as [comp] has a serious expressivity weakness.  Consider the following definition of a curried addition function: *)

Definition curriedAdd (n : nat) := Ret (fun m : nat => Ret (n + m)).

(** This definition works fine, but we run into trouble when we try to apply it in a trivial way.
[[
Definition testCurriedAdd := Bnd (curriedAdd 2) (fun f => f 3).
]]

<<
Error: Universe inconsistency.
>>

The problem has to do with rules for inductive definitions that we will study in more detail in Chapter 12.  Briefly, recall that the type of the constructor [Bnd] quantifies over a type [B].  To make [testCurriedAdd] work, we would need to instantiate [B] as [nat -> comp nat].  However, Coq enforces a %\emph{predicativity restriction}% that (roughly) no quantifier in an inductive or co-inductive type's definition may ever be instantiated with a term that contains the type being defined.  Chapter 12 presents the exact mechanism by which this restriction is enforced, but for now our conclusion is that [comp] is fatally flawed as a way of encoding interesting higher-order functional programs that use general recursion. *)

(** * Comparing the Alternatives *)

(** We have seen four different approaches to encoding general recursive definitions in Coq.  Among them there is no clear champion that dominates the others in every important way.  Instead, we close the chapter by comparing the techniques along a number of dimensions.  Every technique allows recursive definitions with termination arguments that go beyond Coq's built-in termination checking, so we must turn to subtler points to highlight differences.

   One useful property is automatic integration with normal Coq programming.  That is, we would like the type of a function to be the same, whether or not that function is defined using an interesting recursion pattern.  Only the first of the four techniques, well-founded recursion, meets this criterion.  It is also the only one of the four to meet the related criterion that evaluation of function calls can take place entirely inside Coq's built-in computation machinery.  The monad inspired by domain theory occupies some middle ground in this dimension, since generally standard computation is enough to evaluate a term once a high enough approximation level is provided.

   Another useful property is that a function and its termination argument may be developed separately.  We may even want to define functions that fail to terminate on some or all inputs.  The well-founded recursion technique does not have this property, but the other three do.

   One minor plus is the ability to write recursive definitions in natural syntax, rather than with calls to higher-order combinators.  This downside of the first two techniques is actually rather easy to get around using Coq's notation mechanism, though we leave the details as an exercise for the reader.  (For this and other details of notations, see Chapter 12 of the Coq 8.4 manual.)

   The first two techniques impose proof obligations that are more basic than termination arguments, where well-founded recursion requires a proof of extensionality and domain-theoretic recursion requires a proof of continuity.  A function may not be defined, and thus may not be computed with, until these obligations are proved.  The co-inductive techniques avoid this problem, as recursive definitions may be made without any proof obligations.

   We can also consider support for common idioms in functional programming.  For instance, the [thunk] monad effectively only supports recursion that is tail recursion, while the others allow arbitrary recursion schemes.

   On the other hand, the [comp] monad does not support the effective mixing of higher-order functions and general recursion, while all the other techniques do.  For instance, we can finish the failed [curriedAdd] example in the domain-theoretic monad. *)

Definition curriedAdd' (n : nat) := Return (fun m : nat => Return (n + m)).

Definition testCurriedAdd := Bind (curriedAdd' 2) (fun f => f 3).

(** The same techniques also apply to more interesting higher-order functions like list map, and, as in all four techniques, we can mix primitive and general recursion, preferring the former when possible to avoid proof obligations. *)

Fixpoint map A B (f : A -> computation B) (ls : list A) : computation (list B) :=
  match ls with
    | nil => Return nil
    | x :: ls' => Bind (f x) (fun x' =>
      Bind (map f ls') (fun ls'' =>
        Return (x' :: ls'')))
  end.

(** remove printing exists *)
Theorem test_map : run (map (fun x => Return (S x)) (1 :: 2 :: 3 :: nil))
  (2 :: 3 :: 4 :: nil).
  exists 1; reflexivity.
Qed.

(** One further disadvantage of [comp] is that we cannot prove an inversion lemma for executions of [Bind] without appealing to an %\emph{axiom}%, a logical complication that we discuss at more length in Chapter 12.  The other three techniques allow proof of all the important theorems within the normal logic of Coq.

Perhaps one theme of our comparison is that one must trade off between, on one hand, functional programming expressiveness and compatibility with normal Coq types and computation; and, on the other hand, the level of proof obligations one is willing to handle at function definition time. *)


Require Import Category.Lib.
Require Import Category.Theory.Category.
Require Import Category.Theory.Morphisms.
Require Import Category.Theory.Functor.

Generalizable All Variables.

Record SetoidObject@{o p} : Type@{max(o+1,p+1)} := {
  carrier :> Type@{o};
  is_setoid :> Setoid@{o p} carrier
}.
#[export] Existing Instance is_setoid.

Record SetoidMorphism@{o h p} `{Setoid@{o p} x} `{Setoid@{o p} y} := {
  morphism :> x → y;
  proper_morphism :> Proper@{h p} (respectful@{h p h p h p} equiv equiv) morphism
}.
#[export] Existing Instance proper_morphism.

Arguments SetoidMorphism {_} _ {_} _.
Arguments morphism {_ _ _ _ _} _.

Definition SetoidMorphism_equiv@{o h p} {x y : SetoidObject@{o p}} :
  crelation@{h p} (SetoidMorphism@{o h p} x y) :=
  fun f g => ∀ x, @equiv@{o p} _ y (f x) (g x).

Arguments SetoidMorphism_equiv {x y} _ _ /.

#[export]
Program Instance SetoidMorphism_Setoid@{o h p} {x y : SetoidObject@{o p}} :
  Setoid@{h p} (SetoidMorphism@{o h p} x y) := {|
  equiv := SetoidMorphism_equiv@{o h p};
|}.
Next Obligation.
  constructor; repeat intro.
  - reflexivity.
  - symmetry.
    apply X.
  - transitivity (y0 x1).
    + apply X.
    + apply X0.
Qed.

Definition setoid_morphism_id@{o h p} {x : SetoidObject@{o p}} :
  SetoidMorphism@{o h p} x x := {|
  morphism := Datatypes.id
|}.

#[export] Hint Unfold setoid_morphism_id : core.

Program Definition setoid_morphism_compose@{o h p} {x y z : SetoidObject@{o p}}
        (g : SetoidMorphism@{o h p} y z)
        (f : SetoidMorphism@{o h p} x y) : SetoidMorphism@{o h p} x z := {|
  morphism := Basics.compose g f
|}.

#[export] Hint Unfold setoid_morphism_compose : core.

Program Definition setoid_morphism_compose_respects@{o h p}
  {x y z : SetoidObject@{o p}} :
  Proper@{h p} (equiv@{h p} ==> equiv@{h p} ==> equiv@{h p})
    (@setoid_morphism_compose x y z).
Proof.
  unfold Proper, respectful.
  simpl; intros.
  rewrite X.
  apply proper_morphism, X0.
Qed.

(* The category of setoids.

       objects: setoids
        arrows: setoid homomorphisms
      identity: typical identity of sets
   composition: composition of set maps, preserving equivalence
 *)
Program Definition Sets@{o h so sh p} : Category@{so sh p} := {|
  obj     := SetoidObject@{o p} : Type@{so};
  hom     := λ x y, SetoidMorphism@{o h p} x y : Type@{sh};
  homset  := @SetoidMorphism_Setoid@{o h p};
  id      := @setoid_morphism_id@{o h p};
  compose := @setoid_morphism_compose@{o h p};

  compose_respects := @setoid_morphism_compose_respects@{o h p}
|}.

Require Import Category.Theory.Isomorphism.

(* An isomorphism between arrows in a category C is an isomorphism of objects
   in the category of set(oid)s, taking [hom] to the be the carrier type, and
   arrow equivalence to be the setoid. By using Sets in this way, we gain the
   fact that the arrows on both sides are respectful of C's notion of arrow
   equivalence. *)
Notation "x ≊ y" := ({| carrier := x |} ≅[Sets] {| carrier := y |})
  (at level 99) : category_scope.

#[export]
Program Instance isomorphism_to_sets_respects
        `{Setoid x} `{Setoid y}
        (iso : @Isomorphism Sets {| carrier := x |} {| carrier := y |}) :
  Proper (equiv ==> equiv) (to iso).
Next Obligation.
  repeat intro.
  destruct iso; simpl in *.
  destruct to; simpl in *.
  rewrite X; reflexivity.
Qed.

#[export]
Program Instance isomorphism_from_sets_respects
        `{Setoid x} `{Setoid y}
        (iso : @Isomorphism Sets {| carrier := x |} {| carrier := y |}) :
  Proper (equiv ==> equiv) (from iso).
Next Obligation.
  repeat intro.
  destruct iso; simpl in *.
  destruct from; simpl in *.
  rewrite X; reflexivity.
Qed.

Ltac morphism :=
  unshelve (refine {| morphism := _ |}; simpl; intros).

Require Import Category.Structure.Terminal.

#[export]
Program Instance Unit_Setoid : Setoid poly_unit := {
  equiv := fun x y => x = y
}.

#[export]
Program Instance Sets_Terminal : @Terminal Sets := {
  terminal_obj := {| carrier := poly_unit |};
  one := fun _ => {| morphism := fun _ => ttt |};
  one_unique := fun x f g => _
}.
Next Obligation. destruct (f x0), (g x0); reflexivity. Qed.

Require Import Category.Structure.Initial.

#[export]
Program Instance False_Setoid : Setoid False.

#[export]
Program Instance Sets_Initial : @Initial Sets := {
  terminal_obj := {| carrier := False |};
  one := _
}.
Next Obligation.
  construct.
  - contradiction.
  - proper.
Qed.
Next Obligation. contradiction. Qed.

Require Import Category.Structure.Monoidal.

#[export]
Program Instance Sets_Product_Monoidal : @Monoidal Sets := {
  I      := {| carrier := poly_unit |};
  tensor := {|
    fobj := fun p =>
      {| carrier := carrier (fst p) * carrier (snd p)
       ; is_setoid := _
       |};
    fmap := fun x y f =>
      {| morphism := fun p => (fst f (fst p), snd f (snd p))
       ; proper_morphism := _ |}
  |}
}.
Next Obligation.
  construct.
  - repeat intro.
    destruct s, s0.
    try rename X into H.
    try rename X0 into H0.
    exact (fst H ≈ fst H0 ∧ snd H ≈ snd H0).
  - simpl.
    equivalence.
Defined.
Next Obligation.
  proper; simpl in *.
  - destruct s.
    now rewrites.
  - destruct s0.
    now rewrites.
Qed.
Next Obligation.
  construct.
  - construct.
    + try rename X into H.
      now destruct H.
    + proper.
  - construct.
    + split; [ exact ttt | assumption ].
    + proper.
  - simpl.
    reflexivity.
  - simpl.
    destruct x0.
    simpl.
    destruct p.
    split; reflexivity.
Defined.
Next Obligation.
  construct.
  - construct.
    + try rename X into H.
      now destruct H.
    + proper.
  - construct.
    + split; [ assumption | exact ttt ].
    + proper.
  - simpl.
    reflexivity.
  - simpl.
    destruct x0.
    simpl.
    destruct p.
    split; reflexivity.
Defined.
Next Obligation.
  construct.
  - construct.
    + simplify; auto.
    + proper.
  - construct.
    + simplify; auto.
    + proper.
  - simpl.
    simplify; simpl; cat.
  - simpl.
    simplify; simpl; cat.
Defined.

Definition unit_setoid_object@{t u} : SetoidObject@{t u} :=
  {| carrier   := poly_unit@{t}
   ; is_setoid := unit_setoid@{t u} |}.

Lemma injectivity_is_monic {X Y : SetoidObject} (f : X ~{Sets}~> Y) :
  (∀ x y : X, f x ≈ f y → x ≈ y) ↔ Monic f.
Proof.
  split.
  - intros HA.
    constructor.
    autounfold in *; intros ??? HB.
    simpl in *; intros.
    apply HA, HB.
  - intros HA ?? HB.
    given (const_x : unit_setoid_object ~{ Sets }~> X). {
      construct.
      - apply x.
      - proper.
    }
    given (const_y : unit_setoid_object ~{ Sets }~> X). {
      construct.
      - apply y.
      - proper.
    }
    destruct HA.
    specialize (monic unit_setoid_object const_x const_y).
    unfold const_x in monic.
    unfold const_y in monic.
    simpl in *.
    eapply monic; eauto.
    constructor.
Qed.

Lemma surjectivity_is_epic@{h p} {A B : SetoidObject@{p p}}
  (h : A ~{Sets}~> B) :
  (∀ b, ∃ a, h a ≈ b)%type ↔ Epic@{h p} h.
Proof.
  split.
  - intros HA.
    constructor.
    autounfold in *; intros ??? HB.
    simpl in *; intros.
    specialize (HA x).
    destruct HA as [? HA].
    rewrite <- HA.
    apply HB.
  - (* This constructive proof was given by
       aws (https://mathoverflow.net/users/30790/aws)
       In the category of sets epimorphisms are surjective - Constructive Proof?
       URL (version: 2014-08-18): https://mathoverflow.net/q/178786 *)
    intros [epic] ?.
    given (C : SetoidObject). {
      refine {|
        carrier := Type;
        is_setoid := {|
          equiv p q := p ↔ q
        |}
      |}.
      equivalence.
    }
(*
    given (f : B ~{Sets}~> C). {
      refine {|
        morphism := λ b, ∃ a, h a ≈ b
      |}.
    }
    given (g : B ~{Sets}~> C). {
      refine {|
        morphism := λ _, True
      |}.
    }
    specialize (epic C f g).
    enough ((f ∘[Sets] h) ≈ (g ∘[Sets] h)). {
      specialize (epic X b); clear X.
      unfold f, g in epic.
      simpl in *.
      now rewrite epic.
    }
    intro.
    unfold f, g; simpl.
*)
Abort.


From Hammer Require Import Hammer.

Require Coq.Logic.Eqdep_dec.
Require EquivDec.
Require Import ExtLib.Core.RelDec.
Require Import ExtLib.Tactics.Consider.

Set Implicit Arguments.
Set Strict Implicit.

Section Classes.
Context {A : Type}.
Context {dec : EquivDec.EqDec A (@eq A)}.

Theorem UIP_refl : forall {x : A} (p1 : x = x), p1 = refl_equal _.
intros.
eapply Coq.Logic.Eqdep_dec.UIP_dec. apply EquivDec.equiv_dec.
Qed.

Theorem UIP_equal : forall {x y : A} (p1 p2 : x = y), p1 = p2.
eapply Coq.Logic.Eqdep_dec.UIP_dec. apply EquivDec.equiv_dec.
Qed.

Lemma inj_pair2 :
forall (P:A -> Type) (p:A) (x y:P p),
existT P p x = existT P p y -> x = y.
Proof. hammer_hook "EqDep" "EqDep.inj_pair2".
intros. eapply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec; auto.
Qed.

Theorem equiv_dec_refl_left : forall a, @EquivDec.equiv_dec _ _ _ dec a a = left eq_refl.
Proof. hammer_hook "EqDep" "EqDep.equiv_dec_refl_left".
intros. destruct (EquivDec.equiv_dec a a); try congruence.
f_equal. apply UIP_equal.
Qed.

End Classes.

Section from_rel_dec.
Variable T : Type.
Variable RD : RelDec (@eq T).
Variable RDC : RelDec_Correct RD.

Global Instance EqDec_RelDec : EquivDec.EqDec T (@eq T).
Proof. hammer_hook "EqDep" "EqDep.EqDec_RelDec".
red; intros.
consider (x ?[ eq ] y); intros; subst; auto.
left. reflexivity.
Qed.
End from_rel_dec.


(* Bishop-finiteness is that "default" notion of finiteness in the HoTT library *)
Require Import HoTT HitTactics.
Require Import FSets interfaces.lattice_interface.
From subobjects Require Import sub k_finite.

Section finite_hott.
  Variable (A : Type).
  Context `{Univalence}.

  (* A subobject is B-finite if its extension is B-finite as a type *)
  Definition Bfin (X : Sub A) : hProp := BuildhProp (Finite {a : A & a ∈ X}).

  Global Instance singleton_contr a `{IsHSet A} : Contr {b : A & b ∈ {|a|}}.
  Proof.
    exists (a; tr idpath).
    intros [b p].
    simple refine (Trunc_ind (fun p => (a; tr 1%path) = (b; p)) _ p).
    clear p; intro p ; simpl.
    apply path_sigma_hprop; simpl.
    apply p^.
  Defined.

  Definition singleton_fin_equiv' a : Fin 1 -> {b : A & b ∈ {|a|}}.
  Proof.
    intros _. apply (a; tr idpath).
  Defined.

  Global Instance singleton_fin_equiv a `{IsHSet A} : IsEquiv (singleton_fin_equiv' a).
  Proof. apply _. Defined.

  Definition singleton `{IsHSet A} : closedSingleton Bfin.
  Proof.
    intros a.
    simple refine (Build_Finite _ 1 _).
    apply tr.
    symmetry.
    refine (BuildEquiv _ _ (singleton_fin_equiv' a) _).
  Defined.

  Definition empty_finite : closedEmpty Bfin.
  Proof.
    simple refine (Build_Finite _ 0 _).
    apply tr.
    simple refine (BuildEquiv _ _ _ _).
    intros [a p]; apply p.
  Defined.

  Definition decidable_empty_finite : hasDecidableEmpty Bfin.
  Proof.
    intros X [n f].
    strip_truncations.
    destruct n.
    - refine (tr(inl _)).
      apply path_forall. intro z.
      apply path_iff_hprop.
      * intros p.
        contradiction (f (z;p)).
      * contradiction.
    - refine (tr(inr _)).
      apply (tr(f^-1(inr tt))).
  Defined.

  Lemma no_union `{IsHSet A}
        (U : forall (X Y : Sub A),
            Bfin X -> Bfin Y -> Bfin (X ∪ Y))
    : DecidablePaths A.
  Proof.
    intros a b.
    destruct (U {|a|} {|b|} (singleton a) (singleton b)) as [n pn].
    strip_truncations.
    unfold Sect in *.
    destruct pn as [f [g fg gf _]], n as [ | [ | n]].
    - contradiction f.
      exists a.
      apply (tr(inl(tr idpath))).
    - refine (inl _).
      pose (s1 := (a;tr(inl(tr idpath)))
                  : {c : A & Trunc (-1) (Trunc (-1) (c = a) + Trunc (-1) (c = b))}).
      pose (s2 := (b;tr(inr(tr idpath)))
                  : {c : A & Trunc (-1) (Trunc (-1) (c = a) + Trunc (-1) (c = b))}).
      refine (ap (fun x => x.1) (gf s1)^ @ _ @ (ap (fun x => x.1) (gf s2))).
      assert (fs_eq : f s1 = f s2).
      { by apply path_ishprop. }
      refine (ap (fun x => (g x).1) fs_eq).
    - (* Otherwise, ¬(a = b) *)
      refine (inr (fun p => _)).
      pose (s1 := inl (inr tt) : Fin n + Unit + Unit).
      pose (s2 := inr tt : Fin n + Unit + Unit).
      pose (gs1 := g s1).
      pose (c := gs1).
      pose (gs2 := g s2).
      pose (d := gs2).
      assert (Hgs1 : gs1 = c) by reflexivity.
      assert (Hgs2 : gs2 = d) by reflexivity.
      destruct c as [x px'], d as [y py'].
      simple refine (Trunc_ind _ _ px') ; intros px
      ; simple refine (Trunc_ind _ _ py') ; intros py ; simpl.
      enough (s1 = s2) as X.
      {
        unfold s1, s2 in X.
        contradiction (inl_ne_inr _ _ X).
      }
      refine ((fg s1)^ @ ap f (Hgs1 @ _ @ Hgs2^) @ fg s2).
      simple refine (path_sigma _ _ _ _ _); [ | apply path_ishprop ]; simpl.
      destruct px as [px | px] ; destruct py as [py | py]
      ; refine (Trunc_rec _ px) ; clear px ; intro px
      ; refine (Trunc_rec _ py) ; clear py ; intro py.
      * apply (px @ py^).
      * refine (px @ p @ py^).
      * refine (px @ p^ @ py^).
      * apply (px @ py^).
  Defined.
End finite_hott.

Section singleton_set.
  Variable (A : Type).
  Context `{Univalence}.

  Variable (HA : forall a, {b : A & b ∈ {|a|}} <~> Fin 1).

  Definition el x : {b : A & b ∈ {|x|}} := (x;tr idpath).

  Theorem single_bfin_set : forall (x : A) (p : x = x), p = idpath.
  Proof.
    intros x p.
    specialize (HA x).
    pose (el x) as X.
    pose (ap HA^-1 (ap HA (path_sigma _ X X p (path_ishprop _ _)))) as q.
    assert (p = ap (fun z => z.1) ((eissect HA X)^ @ q @ eissect HA X)) as H1.
    {
      unfold q.
      rewrite <- ap_compose.
      enough(forall r,
                (eissect HA X)^
                @ ap (fun x0 : {b : A & b ∈ {|x|}} => HA^-1 (HA x0)) r
                  @ eissect HA X = r
            ) as H2.
      {
        rewrite H2.
        refine (@pr1_path_sigma _ _ X X p _)^.
      }
      induction r.
      hott_simpl.
    }
    assert (idpath = ap (fun z => z.1) ((eissect HA X)^ @ idpath @ eissect HA X)) as H2.
    { hott_simpl. }
    rewrite H1, H2.
    repeat f_ap.
    unfold q.
    enough (ap HA (path_sigma (fun b : A => b ∈ {|x|}) X X p (path_ishprop _ _)) = idpath) as H3.
    {
      rewrite H3.
      reflexivity.
    }
    apply path_ishprop.
  Defined.

  Global Instance set_singleton : IsHSet A.
  Proof.
    refine hset_axiomK.
    unfold axiomK.
    apply single_bfin_set.
  Defined.
End singleton_set.

Section empty.
  Variable (A : Type).
  Variable (X : A -> hProp)
           (Xequiv : {a : A & a ∈ X} <~> Fin 0).
  Context `{Univalence}.

  Lemma X_empty : X = ∅.
  Proof.
    apply path_forall.
    intro z.
    apply path_iff_hprop ; try contradiction.
    intro x.
    destruct Xequiv as [f fequiv].
    contradiction (f(z;x)).
  Defined.
End empty.

Section split.
  Context `{Univalence}.
  Variable (A : Type).
  Variable (P : A -> hProp)
           (n : nat)
           (f : {a : A & P a } <~> Fin n + Unit).

  Definition split : exists P' : Sub A, exists b : A,
        ({a : A & P' a} <~> Fin n) * (forall x, P x = (P' x ∨ merely (x = b))).
  Proof.
    pose (fun x : A => sig (fun y : Fin n => x = (f^-1 (inl y)).1)) as P'.
    assert (forall x, IsHProp (P' x)).
    {
      intros a. unfold P'.
      apply hprop_allpath.
      intros [x px] [y py].
      pose (p := px^ @ py).
      assert (p2 : p # (f^-1 (inl x)).2 = (f^-1 (inl y)).2).
      { apply path_ishprop. }
      simple refine (path_sigma' _ _ _).
      - apply path_sum_inl with Unit.
        refine (transport (fun z => z = inl y) (eisretr f (inl x)) _).
        refine (transport (fun z => _ = z) (eisretr f (inl y)) _).
        apply (ap f).
        apply path_sigma_hprop. apply p.
      - rewrite transport_paths_FlFr.
        hott_simpl; cbn.
        rewrite ap_compose, (ap_compose inl f^-1).
        rewrite ap_inl_path_sum_inl.
        repeat (rewrite transport_paths_FlFr; hott_simpl).
        rewrite !ap_pp.
        rewrite ap_V.
        rewrite <- !other_adj.
        rewrite <- (ap_compose f (f^-1)).
        rewrite ap_equiv.
        rewrite !ap_pp.
        rewrite ap_pr1_path_sigma_hprop.
        rewrite !concat_pp_p.
        rewrite !ap_V.
        rewrite concat_Vp.
        rewrite (concat_p_pp (ap pr1 (eissect f (f^-1 (inl x))))^).
        rewrite concat_Vp.
        hott_simpl.
    }
    exists (fun a => BuildhProp (P' a)).
    exists (f^-1 (inr tt)).1.
    split.
    { unshelve eapply BuildEquiv.
      { refine (fun x => x.2.1). }
      apply isequiv_biinv.
      unshelve esplit;
        exists (fun x => (((f^-1 (inl x)).1; (x; idpath)))).
      - intros [a [y p]]; cbn.
        eapply path_sigma with p^.
        apply path_ishprop.
      - intros x.
        reflexivity.
    }
    { intros a.
      unfold P'.
      apply path_iff_hprop.
      - intros Ha.
        pose (y := f (a;Ha)).
        assert (Hy : y = f (a; Ha)) by reflexivity.
        destruct y as [y | []].
        + refine (tr (inl _)).
          exists y.
          rewrite Hy.
          by rewrite eissect.
        + refine (tr (inr (tr _))).
          rewrite Hy.
          by rewrite eissect.
      - intros Hstuff.
        strip_truncations.
        destruct Hstuff as [[y Hy] | Ha].
        + rewrite Hy.
          apply (f^-1 (inl y)).2.
        + strip_truncations.
          rewrite Ha.
          apply (f^-1 (inr tt)).2. }
  Defined.
End split.

Arguments Bfin {_} _.
Arguments split {_} {_} _ _ _.

Section Bfin_no_singletons.
  Definition S1toSig (x : S1) : {x : S1 & merely(x = base)}.
  Proof.
    exists x.
    simple refine (S1_ind (fun z => merely(z = base)) (tr idpath) _ x).
    apply path_ishprop.
  Defined.

  Instance S1toSig_equiv : IsEquiv S1toSig.
  Proof.
    apply isequiv_biinv.
    split.
    - exists (fun x => x.1).
      simple refine (S1_ind _ idpath _) ; simpl.
      rewrite transport_paths_FlFr.
      hott_simpl.
    - exists (fun x => x.1).
      intros [z x].
      simple refine (path_sigma _ _ _ _ _) ; simpl.
      * reflexivity.
      * apply path_ishprop.
  Defined.

  Theorem no_singleton `{Univalence} (Hsing : Bfin {|base|}) : Empty.
  Proof.
    destruct Hsing as [n equiv].
    strip_truncations.
    assert (S1 <~> Fin n) as X.
    { apply (equiv_compose equiv S1toSig). }
    assert (IsHSet S1) as X1.
    {
      rewrite (path_universe X).
      apply _.
    }
    enough (idpath = loop).
    - assert (S1_encode _ idpath = S1_encode _ (loopexp loop (pos Int.one))) as H' by f_ap.
      rewrite S1_encode_loopexp in H'. simpl in H'. symmetry in H'.
      apply (pos_neq_zero H').
    - apply set_path2.
  Defined.
End Bfin_no_singletons.

(* If A has decidable equality, then every Bfin subobject has decidable membership *)
Section dec_membership.
  Variable (A : Type).
  Context `{MerelyDecidablePaths A} `{Univalence}.

  Global Instance DecidableMembership (P : Sub A) (Hfin : Bfin P) (a : A) :
    Decidable (a ∈ P).
  Proof.
    destruct Hfin as [n Hequiv].
    strip_truncations.
    revert Hequiv.
    revert P.
    induction n.
    - intros.
      pose (X_empty _ P Hequiv) as p.
      rewrite p.
      apply _.
    - intros.
      destruct (split P n Hequiv) as
        (P' & b & HP' & HP).
      unfold member, sub_membership.
      rewrite (HP a).
      destruct (IHn P' HP') as [IH | IH].
      * apply (inl (tr (inl IH))).
      * destruct (m_dec_path a b) as [Hab | Hab].
      + apply (inl (tr (inr Hab))).
      + refine (inr(fun a => _)).
        strip_truncations.
        destruct a as [? | t] ; [ | strip_truncations] ; try contradiction.
        contradiction (Hab (tr t)).
  Defined.
End dec_membership.

Section bfin_kfin.
  Context `{Univalence}.

  Lemma bfin_to_kfin : forall (B : Type), Finite B -> Kf B.
  Proof.
    apply finite_ind_hprop.
    - apply _.
    - apply Kf_unfold.
      exists ∅. intros [].
    - intros B [n f] IH.
      apply Kf_sum ; try assumption.
      apply Kf_Unit.
  Defined.

  Definition bfin_to_kfin_sub A : forall (P : Sub A), Bfin P -> Kf_sub _ P.
  Proof.
    intros P [n f].
    strip_truncations.
    revert f. revert P.
    induction n; intros P f.
    - exists ∅.
      apply path_forall; intro a; simpl.
      apply path_iff_hprop; [ | contradiction ].
      intros p.
      apply (f (a;p)).
    - destruct (split P n f) as
        (P' & b & HP' & HP).
      destruct (IHn P' HP') as [Y HY].
      exists (Y ∪ {|b|}).
      apply path_forall; intro a. simpl.
      rewrite <- HY.
      apply HP.
  Defined.
End bfin_kfin.

Section kfin_bfin.
  Variable (A : Type).
  Context `{DecidablePaths A} `{Univalence}.

  Lemma notIn_ext_union_singleton (b : A) (Y : Sub A) :
    ~ (b ∈ Y) ->
    {a : A & a ∈ ({|b|} ∪ Y)} <~> {a : A & a ∈ Y} + Unit.
  Proof.
    intros HYb.
    unshelve eapply BuildEquiv.
    - intros [a Ha]. cbn in Ha.
      destruct (dec (BuildhProp (a = b))) as [Hab | Hab].
      + apply (inr tt).
      + refine (inl(a;_)).
        strip_truncations.
        destruct Ha as [HXa | HYa].
        * refine (Empty_rec _).
          strip_truncations.
          by apply Hab.
        * apply HYa.
    - apply isequiv_biinv.
      unshelve esplit ; (unshelve eexists
                         ; [intros [[a Ha] | []]
                            ; [apply (a;(tr(inr Ha))) | apply (b;(tr(inl (tr idpath))))]
                           | ]).
      + intros [a Ha]; cbn.
        strip_truncations.
        simple refine (path_sigma' _ _ _); [ | apply path_ishprop ].
        destruct (H a b); cbn.
        * apply p^.
        * reflexivity.
      + intros [[a Ha] | []]; cbn.
        destruct (dec (a = b)) as [Hb | Hb]; cbn.
        * refine (Empty_rec _).
          rewrite Hb in Ha.
          apply (HYb Ha).
        * reflexivity.
        * destruct (dec (b = b)) ; [ reflexivity | contradiction ].
  Defined.

  Theorem bfin_union : @closedUnion A Bfin.
  Proof.
    intros X Y [n fX] HY.
    strip_truncations.
    revert fX. revert X.
    induction n; intros X fX.
    - rewrite (X_empty _ X fX), (neutralL_max (Sub A)).
      apply HY.
    - destruct (split X n fX) as
        (X' & b & HX' & HX).
      assert (Bfin (X'∪ Y)) by (by apply IHn).
      destruct (dec (b ∈ (X' ∪ Y))) as [HX'Yb | HX'Yb].
      + cut (X ∪ Y = X' ∪ Y).
        { intros HXY. rewrite HXY. assumption. }
        apply path_forall. intro a.
        unfold union, sub_union, max_fun.
        rewrite HX.
        rewrite (commutativity (X' a)).
        rewrite (associativity _ (X' a)).
        apply path_iff_hprop.
        * intros Ha.
          strip_truncations.
          destruct Ha as [HXa | HYa]; [ | assumption ].
          strip_truncations.
          rewrite HXa.
          by apply tr.
        * intros Ha.
          apply (tr (inr Ha)).
      + destruct (IHn X' HX') as [n' fw].
        strip_truncations.
        exists (n'.+1).
        apply tr.
        transitivity ({a : A & a ∈ (fun a => merely (a = b)) ∪ (X' ∪ Y)}).
        * apply equiv_functor_sigma_id.
          intro a.
          rewrite <- (associative_max (Sub A)).
          assert (X = X' ∪ (fun a => merely (a = b))) as HX_.
          ** apply path_forall. intros ?.
             unfold union, sub_union, max_fun.
             apply HX.
          ** rewrite HX_, <- (commutative_max (Sub A) X').
             reflexivity.
        * etransitivity.
          { apply (notIn_ext_union_singleton b _ HX'Yb). }
            by rewrite ((equiv_path _ _)^-1 fw).
  Defined.

  Definition FSet_to_Bfin : forall (X : FSet A), Bfin (map X).
  Proof.
    hinduction; try (intros; apply path_ishprop).
    - exists 0.
      apply tr.
      simple refine (BuildEquiv _ _ _ _).
      destruct 1 as [? []].
    - apply _.
    - intros.
      apply bfin_union ; assumption.
  Defined.
End kfin_bfin.

Global Instance Kf_to_Bf (X : Type) `{Univalence} `{DecidablePaths X} (Hfin : Kf X) : Finite X.
Proof.
  destruct (Kf_unfold _ Hfin) as [Y HY].
  simple refine (finite_equiv' _ _ (FSet_to_Bfin _ Y)).
  unshelve esplit.
  - apply (fun z => z.1).
  - apply isequiv_biinv.
    split.
    * exists (fun a => (a;HY a)).
      intros [b Hb].
      apply path_sigma' with idpath.
      apply path_ishprop.
    * refine (fun a => (a;HY a);fun _ => _).
      reflexivity.
Defined.