(** * Tactics for coinductive n-ary relations *)

(**
we provide three tactics:
- [coinduction R H] to start a proof by coinduction
  [R] is a name for the bisimulation candidate,
  [H] is an introduction pattern for the properties of the candidate
- [accumulate H] to accumulate new pairs in the bisimulation candidate
  [H] is an introduction pattern, as above
- [symmetric] to reason by symmetry when the coinductive (binary) relation is defined by a symmetric function.
  this tactics makes it possible to play only half of the coinductive game, provided it manages to prove automatically that the candidate is symmetric.
  A tactic [tac] for solving the symmetry requirement may be passed as follows:
  [symmetric using tac]
  (by default, we use solve[clear;firstorder])
*)

Require Import lattice tower rel.
Set Implicit Arguments.

(** * Arities and relations *)
(** we call 'relations' elements whose type is of the shape
    - [X1 -> X2 -> ... -> Xn -> Prop]
    - or more generally, [forall x1: X1, forall x2: X2, ..., Xn -> Prop]
    those are reified via the definition [REL] below, using "arities" of the shape
    - [ABS X1 (fun _ => ABS X2 (fun _ => ... (ABS Xn (fun _ => PRP))))]
    - [ABS X1 (fun x1 => ABS X2 (fun x2 => ... (ABS Xn (fun _ => PRP))))]
 *)

(** (dependent) arities *)
Inductive Arity :=
| PRP
| ABS(B: Type)(Q: B -> Arity).
Arguments ABS _ _: clear implicits.
(** non-dependent case *)
Notation ABS' B Q := (ABS B (fun _ => Q)).

(** Coq corresponding relation types,
    the [K] argument of [REL'] is mostly instantiated with [Prop], as in [REL] below *)
Fixpoint REL' A K :=
  match A with
  | PRP => K
  | ABS B Q => forall b, REL' (Q b) K
  end.
Notation REL A := (REL' A Prop).

(** corresponding complete lattice structure *)
#[local] Instance CompleteLatticeREL A: CompleteLattice (REL A).
Proof.
  revert A. fix f 1; destruct A; simpl.
  apply CompleteLattice_Prop.
  apply CompleteLattice_dfun; auto.
Defined.

(** (dependent) product type corresponding to the given arity, for curried operations *)
Fixpoint PRD A: Type :=
  match A with
  | PRP => unit
  | ABS B Q => sigT (fun b => PRD (Q b))
  end.

(** currying *)
Fixpoint curry [A K]: REL' A K -> PRD A -> K :=
  match A with
  | PRP => fun R _ => R
  | ABS B Q => fun R x => let (b,q) := x in curry (R b) q
  end.

(** uncurrying *)
Fixpoint uncurry [A K]: (PRD A -> K) -> REL' A K :=
  match A with
  | PRP => fun k => k tt
  | ABS B Q => fun k x => uncurry (fun p => k (existT _ x p))
  end.

(* note: the two lemmas below could be generalised to [REL'] *)
Lemma curryK [A] (R: REL A): uncurry (curry R) == R.
Proof.
  induction A; cbn.
  - reflexivity.
  - intro b. apply H.
Qed.

Lemma uncurry_leq [A] (h k: PRD A -> Prop): uncurry h <= uncurry k <-> h <= k.
Proof.
  induction A; cbn.
  - split. now intros ? []. now intro.
  - split.
    -- intros H' [b q].
       apply (H b (fun q => h (existT _ b q)) (fun q => k (existT _ b q))). apply H'.
    -- intros H' b. apply H. intro q. apply H'.
Qed.

(** helper for the OCaml plugin: [prd A] produces tuples for arity [A] *)
Definition tuple A: REL' A (PRD A) := uncurry (fun x => x).

(** singleton relation *)
Definition EQ {A} (p: PRD A): REL A := uncurry (eq p).

Lemma EQ_spec A (T: REL A) x: EQ x <= T <-> curry T x.
Proof.
  unfold EQ.
  rewrite <-(curryK T) at 1.
  rewrite uncurry_leq. split.
  intros H. now apply H.
  now intros ? ? <-.
Qed.

(** * reification tools to transform propositions in the language of
      gallina into relation containments, e.g.,

      [forall x y: X, R (x+y) (y+x+x)]
      becomes
      [{(x+y, y+x+x) | x,y\in X } <= R]

      [forall x y: X, R (x+y) y /\ R x y]
      becomes
      [{(x+y, y) | x,y: X } \cup {(x, y) | x,y: X } <= R]

*)
Module reification.

 (** dependently typed syntax for formulas of the shape
     forall x y, R t1 t2 /\ forall z, R s1 s2 *)
 Inductive T :=
 | hol
 | abs(B: Type)(Q: B -> T)
 | cnj(H K: T).
 Arguments abs _ _: clear implicits.

 Fixpoint fT A c :=
   match c with
   | hol => PRD A
   | abs B Q => forall b: B, fT A (Q b)
   | cnj H K => (fT A H * fT A K)%type
   end.

 Fixpoint pT [A c] (R: REL A): fT A c -> Prop :=
   match c with
   | hol => curry R
   | abs _ _ => fun x => forall b, pT R (x b)
   | cnj _ _ => fun xy => let (x,y) := xy in pT R x /\ pT R y
   end.

 Fixpoint rT [A c]: fT A c -> REL A :=
   match c with
   | hol => EQ
   | abs _ _ => fun z => sup' top (fun b => rT (z b))
   | cnj _ _ => fun z => let (x,y) := z in cup (rT x) (rT y)
   end.

 (** key property of the above functions *)
 Proposition eT A c R (x: fT A c): pT R x <-> rT x <= R.
 Proof.
   induction c; cbn; symmetry.
   - apply EQ_spec.
   - setoid_rewrite H. rewrite sup_spec. firstorder.
   - destruct x. rewrite IHc1, IHc2. apply cup_spec.
 Qed.

 (* examples on how to use eT/pT *)
 (*
 Goal forall R: relation nat, forall x y, R (x+y) (y+x+x).
   intro R.
   change (let A := (ABS' nat (ABS' nat PRP)) in @pT A
               (abs _ (fun x => abs _ (fun y => hol))) R
               (fun x y => tuple A (x+y) (y+x+x))).
 Abort.

 Goal forall R: relation nat, forall x y, R (x+y) y /\ R x y.
   intro R.
   change (let A := (ABS' nat (ABS' nat PRP)) in @pT A
               (abs _ (fun x => abs _ (fun y => cnj hol hol))) R
               (fun x y => (tuple A (x+y) y, tuple A x y))).
 Abort.

 Goal forall R: relation nat, forall x y, R (x+y) y /\ R x y.
   intro R.
   change (let A := (ABS' nat (ABS' nat PRP)) in @pT A
              (abs _ (fun x => abs _ (fun y => cnj hol hol))) R
              (fun x y => (tuple A (x+y) y, tuple A x y))).
   apply (eT (ABS' nat (ABS' nat PRP))
             (abs _ (fun x => abs _ (fun y => cnj hol hol)))).
   Restart.
   intro R.
   apply (let A := (ABS' nat (ABS' nat PRP)) in @eT A
             (abs _ (fun x => abs _ (fun y => cnj hol hol)))
             R
             (fun x y => (tuple A (x+y) y, tuple A x y))).
 Abort.
 *)

 (** ** tools for the [coinduction] tactic *)

 (**  *)
 Lemma inf_closed_pT A c (x: fT A c): inf_closed (fun y => pT y x).
 Proof.
   intros T HT.
   rewrite eT. apply inf_spec. intros R TR.
   rewrite <-eT. apply HT, TR.
 Qed.

 (** reformulation of the tower induction lemma using reified terms
     for the tactic [coinduction]
     not used in practice, it is subsumed by Proposition [ptower] below *)
 Proposition tower A c (b: mon (REL A)) (x: fT A c):
     (forall R: Chain b, pT `R x -> pT (b `R) x) ->
     (pT (gfp b) x).
 Proof.
   intro H.
   cut (forall R: Chain b, pT `R x). intros E. apply E.
   apply (tower (inf_closed_pT _ _ x)). apply H.
 Qed.

 (* idea: the above lemma can be used as follows: *)
 (*
 Section s.
  Variable b: mon (nat -> nat -> Prop).
  Goal forall n m (k: n=m), gfp b (n+n) (m+m) /\ forall k, gfp b (n+k) (k+m).
    apply (let A := ABS' nat (ABS' nat PRP) in
           tower A
            (abs nat (fun n =>
             abs nat (fun m =>
             abs (n=m) (fun _ =>
                          cnj hol (abs nat (fun _ => hol))))))
            ((fun n m _ => (tuple A (n+n) (m+m), fun k => tuple A (n+k) (k+m))))
          ).
    simpl pT.
    intros R HR.
  Abort.
 End s.
  *)

 (** ** tools for the [accumulate] tactic *)

 (** in order to implement the accumulation rule,
     we also need to record the existing assumptions about the current candidate
     we do so using "lists of [T]s" ([Ts]), which we can later merge into a single relation
  *)
 Inductive Ts A :=
 | tnil
 | tcons [c] (x: fT A c) (Q: Ts A).
 (** semantics of [Ts], as hypotheses  *)
 Fixpoint pTs A (cs: Ts A) (R: REL A) (P: Prop): Prop :=
   match cs with
   | tnil _ => P
   | tcons x cs => pT R x -> pTs cs R P
   end.
 Fixpoint merge A (cs: Ts A): REL A :=
   match cs with
   | tnil _ => bot
   | tcons x cs => cup (rT x) (merge cs)
   end.
 (** key lemma about the above functions  *)
 Lemma eTs A (cs: Ts A) R P: pTs cs R P <-> (merge cs <= R -> P).
 Proof.
   induction cs.
   - split. trivial. intro H; apply H. apply leq_bx.
   - simpl pTs. simpl merge. rewrite cup_spec, IHcs, eT. tauto.
 Qed.
 (** in order to add the current goal as an hypothesis *at the end of the goal*,
     we need an operation to insert it *at the end of a list* *)
 Fixpoint tsnoc [A] cs [c] (x: fT A c) :=
   match cs with
   | tnil _ => tcons x (tnil A)
   | tcons x' cs => tcons x' (tsnoc cs x)
   end.
 Lemma merge_tsnoc A cs c x: merge (@tsnoc A cs c x) == merge (tcons x cs).
 Proof.
   induction cs.
   - reflexivity.
   - simpl tsnoc. simpl merge.
     rewrite IHcs. simpl merge. now rewrite cupA, (cupC (rT _)), <-cupA.
 Qed.

 (** reformulation of the relativised tower induction lemma using reified terms
     this is the lemma which is applied in tactic [accumulate] *)
 Proposition ptower A (b: mon (REL A)) cs c (x: fT A c):
     (forall R: Chain b, pTs (tsnoc cs x) `R (pT (b `R) x)) ->
     (forall R: Chain b, pTs cs `R (pT `R x)).
 Proof.
   setoid_rewrite eTs.
   setoid_rewrite merge_tsnoc.
   intro H.
   refine (ptower _ (inf_closed_pT _ _ _) _).
   intros R HR Hyps. apply H; trivial.
   cbn; apply cup_spec. now rewrite <-eT.
 Qed.

 (** ** tools for the [symmetric] tactic *)

 Section sym.
   Variable A: Type.
   Let A2 := ABS A (fun _ => ABS A (fun _ => PRP)).

   (** converse operation on [fT] *)
   Fixpoint converse_fT [c]: fT A2 c -> fT A2 c :=
     match c with
     | hol => fun z => let 'existT _ x (existT _ y _) := z in tuple A2 y x
     | abs _ _ => fun x b => (converse_fT (x b))
     | cnj _ _ => fun z => let (x,y) := z in (converse_fT x,converse_fT y)
     end.

   Lemma existT_nodep_eq (a b: A) T (x y: T):
     existT (fun _ => T) a x = existT (fun _ => T) b y <->  a = b /\ x = y.
   Proof. split. intro H. inversion H. tauto. intuition congruence. Qed.

   Lemma converse_rT c (x: fT A2 c): converse (rT x) == rT (converse_fT x).
   Proof.
     induction c; simpl rT; intros i j.
     - destruct x as (x,(y,[])). cbn.
       rewrite 4existT_nodep_eq. tauto.
     - etransitivity. apply converse_sup. refine (sup_weq _ _).
       reflexivity. intros b. apply H.
     - destruct x. etransitivity. apply converse_cup.
       apply (@cup_weq _ _ _ _ (IHc1 _) _ _ (IHc2 _)).
   Qed.

   (** reformulation of the symmetry lemma using reified terms
       this is the lemma which is applied in tactic [symmetric]
    *)
   Lemma by_symmetry c (x: fT A2 c) {b s: mon (A -> A -> Prop)} {S: Symmetrical converse b s} (R: Chain b):
     (* alternative to the hypothesis below: *)
     (* (forall i j, rT x j i -> rT x i j) -> *)
     (forall R, @pT A2 c R x -> @pT A2 c R (converse_fT x)) ->
     @pT A2 c (s `R) x ->
     @pT A2 c (b `R) x.
   Proof.
     rewrite 2!eT. intros C H. rewrite symmetrical_chain.
     apply cap_spec. split; trivial.
     apply switch. rewrite (converse_rT _ x), <-eT.
     apply C. now rewrite eT.
   Qed.
 End sym.

End reification.

(** * Exported tactics *)

(** registering constants required in the OCaml plugin  *)
Register body                    as coinduction.body.
Register elem                    as coinduction.elem.
Register Chain                   as coinduction.Chain.
Register gfp                     as coinduction.gfp.
Register Symmetrical             as coinduction.Symmetrical.
Register PRP                     as coinduction.PRP.
Register ABS                     as coinduction.ABS.
Register tuple                   as coinduction.tuple.
Register reification.hol         as coinduction.hol.
Register reification.abs         as coinduction.abs.
Register reification.cnj         as coinduction.cnj.
Register reification.fT          as coinduction.fT.
Register reification.pT          as coinduction.pT.
Register reification.tnil        as coinduction.tnil.
Register reification.tcons       as coinduction.tcons.
Register reification.ptower      as coinduction.ptower.
Register reification.by_symmetry as coinduction.by_symmetry.

(** loading the OCaml plugin  *)
Declare ML Module "coq-coinduction.plugin".

(** ** starting a proof by (enhanced) coinduction *)
(** when the goal is of the shape

    [forall x y..., gfp b u v /\ forall z, P -> gfp b s t]

    where x,y... may appear in u, v, P, s, t and z may appear in P, s ,t
    (more complex alternations of quantifiers/conjunctions/implications being allowed)
    and [b] is the function for the considered coinductive relation

    [coinduction R H] moves to a goal

    R: Chain b
    H: forall x y..., `R u v /\ forall z, P -> `R s t
    -------------------------------------------------------
    forall x y..., b `R u v /\ forall z, P -> b `R s t

    [R] should be understood as the bisimulation up-to candidate.
    [H] expresses the pairs [R] is assumed to contain.
    Note the move to [b `R] in the conclusion: now we should play at least one step of the coinductive game for all pairs inserted in the candidate.
    Also note that [H] maybe an introduction pattern.
 *)
(** we use the OCaml defined [apply_ptower] tactic, whose role is:
    - to parse the goal to recognise a bisimulation candidate
    - to `apply' [reification.ptower] with reified arguments corresponding to that candidate
    - to `change' the new goal to get rid of the reified operations and get back to a goal resembling the initial one
    (The last step could be implemented with [simpl reification.pT], but this would result in unwanted additional simplifications, and this resets names of bound variables in a very bad way. This is why we spend time in OCaml to reconstruct a type for the new goal by following syntactically the initial one.)
  *)
Tactic Notation "coinduction" ident(R) simple_intropattern(H) :=
  apply gfp_prop; intro R; apply_ptower R O; intros H.

(** ** accumulating knowledge in a proof by enhanced coinduction *)

(** when the goal is of the shape, typically obtained after starting a proof by coinduction and    performing one step of the coinductive game:

    R: Chain b
    H: forall x y, `R u v
    H': forall x y z, P -> `R s t
    --------------------------------
    forall i j, `R p q

    (more complex alternations of quantifiers/conjunctions/implications being allowed in both hypotheses and conclusion)

    [accumulate H''] moves to a goal

    R: Chain b
    H: forall x y, `R u v
    H': forall x y z, P -> `R s t
    H'': forall i j, `R p q
    --------------------------------
    forall i j, b `R p q

    The conclusion has been saved as an hypothesis [H''],
    and a [b] has been inserted in the conclusion, so that we have to play at least one step of the coinductive game on the added pairs

    Like for [coinduction], [H''] maybe an introduction pattern.
 *)

(** the implementation is a bit more involved:
    - we successively revert all assumptions about this candidate into the conclusion
    - we use the OCaml tactic [apply_ptower] in order to reify the goal, apply [reification.ptower] with appropriate arguments, and get rid of the reified operations
    - then we move the hypotheses back to the context,
    - and we introduce the new hypothesis
  *)
Ltac xaccumulate R n :=
  lazymatch goal with
  | H: context[R] |- _ => revert H; xaccumulate R (S n); intro H
  | _ => apply_ptower R n
  end.

Tactic Notation "accumulate" hyp(R) simple_intropattern(H) :=
  xaccumulate R O; intros H; simpl REL in *.

Tactic Notation "accumulate" simple_intropattern(H) :=
  lazymatch goal with
  | R: Chain _ |- _ => accumulate R H
  | _ => fail "could not find the coinductive candidate"
  end.

(** reasoning on symmetric candidates with symmetric functions *)
(** this tactic makes it possible to play only half of the coinductive game in cases where both the game and the current goal are symmetric:
    - that the game is symmetric is inferred using the typeclasse [Symmetrical]
    - that the goal is symmetric is proven using the given tactic (by default, [firstorder])
    the goal should be of the form
    [forall x y..., b `R u v]
    it moves to a goal of the form
    [forall x y..., s `R u v]
    (where [R: Chain b] with [b] the function for the coinductive game, and [s] the function for the `half of [b]')
    conjunctions are also allowed, like in the other tactics)
 *)
(** as above, we use the OCaml defined tactic [apply_by_symmetry] in order to apply the lemma [reification.by_symmetry] and set the resulting goal back into a user-friendly shape *)
Ltac default_sym_tac := solve[clear;firstorder]||fail "could not get symmetry automatically".
Tactic Notation "symmetric" hyp(R) "using" tactic(tac) :=
  apply_by_symmetry R; [simpl reification.pT; tac|].
Tactic Notation "symmetric" hyp(R) :=
  symmetric R using default_sym_tac.
Tactic Notation "symmetric" "using" tactic(tac) :=
  lazymatch goal with
  | R: Chain _ |- _ => symmetric R using tac
  | _ => fail "could not find the coinductive candidate"
  end.
Tactic Notation "symmetric" :=
  lazymatch goal with
  | R: Chain _ |- _ => symmetric R
  | _ => fail "could not find the coinductive candidate"
  end.

(** performing a single step
    (equivalent to [accumulate _], except that we do not deal with composite candidates and the coinductive proof need not be started) *)
Ltac step := apply sub_bChain; simpl body.


Require Import dot.

(* :! -- directly invertible value typing *)
Inductive vtp(*possible types*) : nat(*pack count*) -> venv -> id -> ty -> nat(*size*) -> Prop :=
| vtp_top: forall m G1 x n1,
    x < length G1 ->
    vtp m G1 x TTop (S n1)
| vtp_typ: forall m G1 x l ds TX T1 T2 n1 n2,
    index x G1 = Some (vobj ds) ->
    index l (dms_to_list ds) = Some (dty TX) ->
    stp [] G1 T1 TX n1 ->
    stp [] G1 TX T2 n2 ->
    vtp m G1 x (TTyp l T1 T2) (S (n1+n2))
| vtp_fun: forall m G1 x l ds dsx OT1 OT2 OT1x OT2x T1 T2 T3 T4 T2' T4' t T1x T2x tx T' T2x' n1 n2 n3 n4,
    index x G1 = Some (vobj ds) ->
    index l (dms_to_list ds) = Some (dfun OT1 OT2 t) ->
    eq_some OT1 T1 ->
    eq_some OT2 T2 ->
    subst_dms x dsx = ds ->
    dms_has_type [T'] G1 dsx T' n4 ->
    subst_dm x (dfun OT1x OT2x tx) = (dfun OT1 OT2 t) ->
    eq_some OT1x T1x ->
    eq_some OT2x T2x ->
    substt x T1x = T1 ->
    substt x T2x = T2 ->
    T2x' = (open 0 (TVar false 1) T2x) ->
    has_type [T1x;T'] G1 tx T2x' n3 ->
    stp [] G1 T3 T1 n1 ->
    T2' = (open 0 (TVar false 0) T2) ->
    T4' = (open 0 (TVar false 0) T4) ->
    closed 0 (length G1) 1 T2 ->
    closed 0 (length G1) 1 T4 ->
    stp [T3] G1 T2' T4' n2 ->
    vtp m G1 x (TFun l T3 T4) (S (n1+n2+n3+n4))
| vtp_bind: forall m G1 x T2 n1,
    vtp m G1 x (open 0 (TVar true x) T2) n1 ->
    closed 0 (length G1) 1 T2 ->
    vtp (S m) G1 x (TBind T2) (S (n1))
| vtp_sel: forall m G1 x y l ds TX n1,
    index y G1 = Some (vobj ds) ->
    index l (dms_to_list ds) = Some (dty TX) ->
    vtp m G1 x TX n1 ->
    vtp m G1 x (TSel (TVar true y) l) (S (n1))
| vtp_and: forall m m1 m2 G1 x T1 T2 n1 n2,
    vtp m1 G1 x T1 n1 ->
    vtp m2 G1 x T2 n2 ->
    m1 <= m -> m2 <= m ->
    vtp m G1 x (TAnd T1 T2) (S (n1+n2))
| vtp_or1: forall m m1 m2 G1 x T1 T2 n1,
    vtp m1 G1 x T1 n1 ->
    closed 0 (length G1) 0 T2 ->
    m1 <= m -> m2 <= m ->
    vtp m G1 x (TOr T1 T2) (S (n1))
| vtp_or2: forall m m1 m2 G1 x T1 T2 n1,
    vtp m1 G1 x T2 n1 ->
    closed 0 (length G1) 0 T1 ->
    m1 <= m -> m2 <= m ->
    vtp m G1 x (TOr T1 T2) (S (n1))
.

Definition vtpd m G1 x T1 := exists n, vtp m G1 x T1 n.

Definition vtpdd m G1 x T1 := exists m1 n, vtp m1 G1 x T1 n /\ m1 <= m.

Hint Constructors vtp.

Ltac euv := match goal with
             | H: vtpd _ _ _ _ |- _ => destruct H as [? H]
             | H: vtpdd _ _ _ _ |- _ => destruct H as [? [? [H ?]]]
            end.

Hint Unfold vtpd.
Hint Unfold vtpdd.

Lemma vtp_all_extend: forall ni,
  (forall m v1 x G1 T2 n,
     vtp m G1 x T2 n -> n < ni ->
     vtp m (v1::G1) x T2 n).
Proof.
  intros n. induction n. repeat split; intros; omega.
  intros; inversion H.
  (* vtp *)
  - econstructor. simpl. eauto.
  - econstructor. eapply index_extend. eauto. eauto. eapply stp_extend. eauto. eapply stp_extend. eauto.
  - econstructor. eapply index_extend. eauto. eauto. eauto. eauto. eauto.
    eapply dms_has_type_extend. eauto. eauto. eauto. eauto. eauto. eauto. eauto.
    eapply has_type_extend. eauto. eapply stp_extend. eauto. eauto. eauto.
    eapply closed_extend. eauto. eapply closed_extend. eauto. eapply stp_extend. eauto.
  - econstructor. eapply IHn. eauto. omega. eapply closed_extend. eauto.
  - econstructor. eapply index_extend. eauto. eauto. eapply IHn. eauto. omega.
  - econstructor. eapply IHn. eauto. omega. eapply IHn. eauto. omega. eauto. eauto.
  - econstructor. eapply IHn. eauto. omega. eapply closed_extend. eauto. omega. eauto.
  - eapply vtp_or2. eapply IHn. eauto. omega. eapply closed_extend. eauto. omega. eauto.
Qed.

Lemma vtp_all_closed: forall ni,
  (forall m x G1 T2 n,
     vtp m G1 x T2 n -> n < ni ->
     x < length G1) /\
  (forall m x G1 T2 n,
     vtp m G1 x T2 n -> n < ni ->
     closed 0 (length G1) 0 T2).
Proof.
  intros n. induction n. repeat split; intros; omega.
  repeat split; intros; inversion H; destruct IHn as [IHV1 IHV2].
  (* vtp left *)
  - eauto.
  - eapply index_max. eauto.
  - eapply index_max. eauto.
  - eapply IHV1. eauto. omega.
  - eapply IHV1. eauto. omega.
  - eapply IHV1. eauto. omega.
  - eapply IHV1. eauto. omega.
  - eapply IHV1. eauto. omega.
  (* vtp right *)
  - econstructor.
  - change 0 with (length ([]:tenv)) at 1. econstructor. eapply stp_closed1. eauto. eapply stp_closed2. eauto.
  - change 0 with (length ([]:tenv)) at 1. econstructor. eapply stp_closed1. eauto. eauto.
  - econstructor. eauto.
  - econstructor. econstructor. eapply index_max. eauto.
  - econstructor. eapply IHV2. eauto. omega. eapply IHV2. eauto. omega.
  - econstructor. eapply IHV2. eauto. omega. eauto.
  - econstructor. eauto. eapply IHV2. eauto. omega.
Qed.

Lemma vtp_extend : forall m v1 x G1 T2 n,
                      vtp m G1 x T2 n ->
                      vtp m (v1::G1) x T2 n.
Proof. intros. eapply vtp_all_extend. eauto. eauto. Qed.

Lemma vtp_closed: forall m G1 x T2 n1,
  vtp m G1 x T2 n1 ->
  closed 0 (length G1) 0 T2.
Proof. intros. eapply vtp_all_closed. eauto. eauto. Qed.

Lemma vtp_closed1: forall m G1 x T2 n1,
  vtp m G1 x T2 n1 ->
  x < length G1.
Proof. intros. eapply vtp_all_closed. eauto. eauto. Qed.

Lemma stp_subst_narrow0: forall n, forall GH G1 T1 T2 TX x n2,
   stp (GH++[TX]) G1 T1 T2 n2 -> x < length G1 -> n2 < n ->
   (forall GH (T3 : ty) (n1 : nat),
      htp (GH++[TX]) G1 0 T3 n1 -> n1 < n ->
      exists m2, vtpd m2 G1 x (substt x T3)) ->
   stpd (map (substt x) GH) G1 (substt x T1) (substt x T2).
Proof.
  intros n. induction n. intros. omega.
  intros ? ? ? ? ? ? ? ? ? ? narrowX.

  (* helper lemma for htp *)
  assert (forall ni n2, forall GH T2 xi,
    htp (GH ++ [TX]) G1 xi T2 n2 -> xi <> 0 -> n2 < ni -> ni < S n ->
    htpd (map (substt x) GH) G1 (xi-1) (substt x T2)) as htp_subst_narrow02. {
      induction ni. intros. omega.
      intros. inversion H2.
      + (* var *) subst.
        repeat eexists. eapply htp_var. eapply index_subst1. eauto. eauto.
        eapply closed_subst0. eapply closed_upgrade_gh. eauto. omega. eauto.
      + (* bind *) subst.
        assert (htpd (map (substt x) (GH0)) G1 (xi-1) (substt x (TBind TX0))) as BB.
        eapply IHni. eapply H6. eauto. omega. omega.
        rewrite subst_open5.
        eu. repeat eexists. eapply htp_unpack. eauto.
        eapply closed_upgrade_gh. eapply closed_subst1. eauto. eauto. eauto. omega.
        apply []. eauto.
      + (* sub *) subst.
        assert (exists GL0, GL = GL0 ++ [TX] /\ GH0 = GU ++ GL0) as A. eapply gh_match1. eauto. omega.
        destruct A as [GL0 [? ?]]. subst GL.
        assert (htpd (map (substt x) GH0) G1 (xi-1) (substt x T3)) as AA.
        eapply IHni. eauto. eauto. omega. omega.
        assert (stpd (map (substt x) GL0) G1 (substt x T3) (substt x T0)) as BB.
        eapply IHn. eauto. eauto. omega. { intros. eapply narrowX. eauto. eauto. }
        eu. eu. repeat eexists. eapply htp_sub. eauto. eauto.
        (* - *)
        rewrite map_length. rewrite app_length in H8. simpl in H8. unfold id in *. omega.
        subst GH0. rewrite map_app. eauto.
  }
  (* special case *)
  assert (forall ni n2, forall T0 T2,
    htp (T0 :: GH ++ [TX]) G1 (length (GH ++ [TX])) T2 n2 -> n2 < ni -> ni < S n ->
    htpd (map (substt x) (T0::GH)) G1 (length GH) (substt x T2)) as htp_subst_narrow0. {
      intros.
      rewrite app_comm_cons in H2.
      remember (T0::GH) as GH1. remember (length (GH ++ [TX])) as xi.
      rewrite app_length in Heqxi. simpl in Heqxi.
      assert (length GH = xi-1) as R. omega.
      rewrite R. eapply htp_subst_narrow02. eauto. omega. eauto. eauto.
  }

  (* main logic *)
  inversion H.
  - Case "bot". subst.
    eapply stpd_bot; eauto. rewrite map_length. simpl. eapply closed_subst0.
    rewrite app_length in H2. simpl in H2. eapply H2. eauto.
  - Case "top". subst.
    eapply stpd_top; eauto. rewrite map_length. simpl. eapply closed_subst0.
    rewrite app_length in H2. simpl in H2. eapply H2. eauto.
  - Case "fun". subst.
    eapply stpd_fun. eauto. eauto.
    rewrite map_length. eapply closed_subst0. rewrite app_length in *. simpl in *. eauto. omega.
    rewrite map_length. eapply closed_subst0. rewrite app_length in *. simpl in *. eauto. omega.
    eapply IHn; eauto. omega.
    rewrite <- subst_open_commute_z. rewrite <- subst_open_commute_z.
    specialize (IHn (T4::GH)). simpl in IHn.
    unfold substt in IHn at 2.  unfold substt in IHn at 3. unfold substt in IHn at 3.
    simpl in IHn. eapply IHn.
    rewrite map_length. rewrite app_length in *. eassumption.
    omega. omega. eauto.
  - Case "typ". subst.
    eapply stpd_typ. eapply IHn; eauto. omega. eapply IHn; eauto. omega.

  - Case "ssel1". subst.
    assert (substt x T2 = T2) as R. eapply subst_closed_id. eapply stpd_closed2 with (GH:=[]). eauto.
    eexists. eapply stp_strong_sel1. eauto. eauto. rewrite R. eauto.

  - Case "ssel2". subst.
    assert (substt x T1 = T1) as R. eapply subst_closed_id. eapply stpd_closed1 with (GH:=[]). eauto.
    eexists. eapply stp_strong_sel2. eauto. eauto. rewrite R. eauto.

  - Case "sel1". subst. (* invert htp to vtp and create strong_sel node *)
    case_eq (beq_nat x0 0); intros E.
    + assert (x0 = 0). eapply beq_nat_true_iff. eauto. subst x0.
      assert (exists m0, vtpd m0 G1 x (substt x (TTyp l TBot T2))) as A. eapply narrowX. eauto. omega.
      destruct A as [? A]. euv. inversion A. subst.
      repeat eexists. eapply stp_strong_sel1. eauto. eauto. unfold substt.
      eauto.
    + assert (x0 <> 0). eapply beq_nat_false_iff. eauto.
      eapply htp_subst_narrow02 in H2.
      eu. repeat eexists. unfold substt. simpl. rewrite E. eapply stp_sel1. eapply H2. eauto. eauto. eauto.

  - Case "sel2". subst. (* invert htp to vtp and create strong_sel node *)
    case_eq (beq_nat x0 0); intros E.
    + assert (x0 = 0). eapply beq_nat_true_iff. eauto. subst x0.
      assert (exists m0, vtpd m0 G1 x (substt x (TTyp l T1 TTop))) as A. eapply narrowX. eauto. omega.
      destruct A as [? A]. euv. inversion A. subst.
      repeat eexists. eapply stp_strong_sel2. eauto. eauto. unfold substt.
      eauto.
    + assert (x0 <> 0). eapply beq_nat_false_iff. eauto.
      eapply htp_subst_narrow02 in H2.
      eu. repeat eexists. unfold substt. simpl. rewrite E. eapply stp_sel2. eapply H2. eauto. eauto. eauto.
  - Case "selx".
    eexists. eapply stp_selx. subst. eapply vr_closed_subst. rewrite app_length in H2. simpl in H2. rewrite map_length. eauto. eauto.

  - Case "bind1".
    assert (stpd (map (substt x) (T1'::GH)) G1 (substt x T1') (substt x T2)) as A.
    eapply IHn; eauto. omega.
    eu. repeat eexists. eapply stp_bind1. eapply A.
    simpl. subst T1'. fold subst. eapply subst_open4.
    fold subst. eapply closed_subst0. rewrite app_length in H4. simpl in H4. rewrite map_length. eauto. eauto.
    eapply closed_subst0. rewrite map_length. rewrite app_length in H5. simpl in H5. eauto. eauto.

  - Case "bindx".
    assert (stpd (map (substt x) (T1'::GH)) G1 (substt x T1') (substt x T2')) as A.
    eapply IHn; eauto. omega.
    eu. repeat eexists. eapply stp_bindx. eapply A.
    subst T1'. fold subst. eapply subst_open4.
    subst T2'. fold subst. eapply subst_open4.
    rewrite app_length in H5. simpl in H5. eauto. eapply closed_subst0. rewrite map_length. eauto. eauto.
    rewrite app_length in H6. simpl in H6. eauto. eapply closed_subst0. rewrite map_length. eauto. eauto.

  - Case "and11".
    assert (stpd (map (substt x) GH) G1 (substt x T0) (substt x T2)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eexists. eapply stp_and11. eauto. eapply closed_subst0. rewrite app_length in H3. rewrite map_length. eauto. eauto.
  - Case "and12".
    assert (stpd (map (substt x) GH) G1 (substt x T3) (substt x T2)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eexists. eapply stp_and12. eauto. eapply closed_subst0. rewrite app_length in H3. rewrite map_length. eauto. eauto.
  - Case "and2".
    assert (stpd (map (substt x) GH) G1 (substt x T1) (substt x T0)). eapply IHn. eauto. eauto. omega. eauto.
    assert (stpd (map (substt x) GH) G1 (substt x T1) (substt x T3)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eu. eexists. eapply stp_and2. eauto. eauto.

  - Case "or21".
    assert (stpd (map (substt x) GH) G1 (substt x T1) (substt x T0)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eexists. eapply stp_or21. eauto. eapply closed_subst0. rewrite app_length in H3. rewrite map_length. eauto. eauto.
  - Case "or22".
    assert (stpd (map (substt x) GH) G1 (substt x T1) (substt x T3)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eexists. eapply stp_or22. eauto. eapply closed_subst0. rewrite app_length in H3. rewrite map_length. eauto. eauto.
  - Case "or1".
    assert (stpd (map (substt x) GH) G1 (substt x T0) (substt x T2)). eapply IHn. eauto. eauto. omega. eauto.
    assert (stpd (map (substt x) GH) G1 (substt x T3) (substt x T2)). eapply IHn. eauto. eauto. omega. eauto.
    eu. eu. eexists. eapply stp_or1. eauto. eauto.

  - Case "trans".
    assert (stpd (map (substt x) GH) G1 (substt x T1) (substt x T3)).
    eapply IHn; eauto. omega.
    assert (stpd (map (substt x) GH) G1 (substt x T3) (substt x T2)).
    eapply IHn; eauto. omega.
    eu. eu. repeat eexists. eapply stp_trans. eauto. eauto.

Grab Existential Variables.
apply 0. apply 0.
Qed.

Lemma stp_subst_narrowX: forall ml, forall nl, forall m GH G1 T2 TX x n1 n2,
   vtp m G1 x (substt x TX) n1 ->
   htp (GH++[TX]) G1 0 T2 n2 -> x < length G1 -> m < ml -> n2 < nl ->
   (forall (m0 : nat) (G1 : venv) x (T2 T3 : ty) (n1 n2 : nat),
        vtp m0 G1 x (substt x T2) n1 ->
        stp [] G1 (substt x T2) (substt x T3) n2 -> m0 <= m ->
        vtpdd m0 G1 x (substt x T3)) ->
   vtpdd m G1 x (substt x T2). (* decrease b/c transitivity *)
Proof.
  intros ml. (* induction ml. intros. omega. *)
  intros nl. induction nl. intros. omega.
  intros.
  inversion H0.
  - Case "var". subst.
    assert (T2 = TX). eapply index_hit0. eauto.
    subst T2.
    repeat eexists. eauto. eauto.
  - Case "unpack". subst.
    assert (vtpdd m G1 x (substt x (TBind TX0))) as A.
    eapply IHnl. eauto. eauto. eauto. eauto. omega. eauto.
    destruct A as [? [? [A ?]]]. inversion A. subst.
    rewrite subst_open_commute0b. repeat eexists. eauto. omega.
  - Case "sub". subst.
    destruct GL.

    assert (vtpdd m G1 x (substt x T1)) as A.
    eapply IHnl. eauto. eauto. eauto. eauto. omega. eauto.
    euv.
    assert (stpd [] G1 (substt x T1) (substt x T2)) as B.
    erewrite subst_closed_id. erewrite subst_closed_id. eexists. eassumption.
    eapply stp_closed2 in H6. simpl in H6. eapply H6.
    eapply stp_closed1 in H6. simpl in H6. eapply H6.
    simpl in B. eu.
    assert (vtpdd x0 G1 x (substt x T2)).
    eapply H4. eauto. eauto. eauto.
    euv. repeat eexists. eauto. omega.

    assert (length GL = 0) as LenGL. simpl in *. omega.
    assert (GL = []). destruct GL. reflexivity. simpl in LenGL. inversion LenGL.
    subst GL.
    assert (TX = t). eapply proj2. apply app_inj_tail. eassumption.
    subst t.
    assert (vtpdd m G1 x (substt x T1)) as A.
    eapply IHnl. eauto. eauto. eauto. eauto. omega. eauto.
    euv.
    assert (stpd (map (substt x) []) G1 (substt x T1) (substt x T2)) as B.
    eapply stp_subst_narrow0. eauto. eauto. eauto. {
      intros. eapply IHnl in H. euv. repeat eexists. eauto. eauto. eauto. eauto. omega. eauto.
    }
    simpl in B. eu.
    assert (vtpdd x0 G1 x (substt x T2)).
    eapply H4. eauto. eauto. eauto.
    euv. repeat eexists. eauto. omega.
Qed.

(* possible types closure *)
Lemma vtp_widen: forall l, forall n, forall k, forall m1 G1 x T2 T3 n1 n2,
  vtp m1 G1 x T2 n1 ->
  stp [] G1 T2 T3 n2 ->
  m1 < l -> n2 < n -> n1 < k ->
  vtpdd m1 G1 x T3.
Proof.
  intros l. induction l. intros. solve by inversion.
  intros n. induction n. intros. solve by inversion.
  intros k. induction k; intros. solve by inversion.
  inversion H.
  - Case "top". inversion H0; subst; invty.
    + SCase "top". repeat eexists; eauto.
    + SCase "ssel2".
      assert (vtpdd m1 G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H9. omega.
    + SCase "and".
      assert (vtpdd m1 G1 x T1). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T0). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T1). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T0). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd m1 G1 x T0) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.
  - Case "typ". inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply index_max. eauto. eauto.
    + SCase "typ". invty. subst.
      repeat eexists. eapply vtp_typ. eauto. eauto.
      eapply stp_trans. eauto. eauto.
      eapply stp_trans. eauto. eauto.
      eauto.
    + SCase "sel2".
      assert (vtpdd m1 G1 x TX0). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H12. omega.
    + SCase "and".
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T5). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T5). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd m1 G1 x T5) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.
  - Case "fun". inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply index_max. eauto. eauto.
    + SCase "fun". invty. subst.
      remember (substt x T2x) as T0.
      assert (stpd [T8] G1 (open 0 (TVar false 0) T0) (open 0 (TVar false 0) T5)) as A. {
        eapply stp_narrow_norec. simpl. eassumption. simpl. eassumption.
      }
      destruct A as [na A].
      repeat eexists. eapply vtp_fun. eauto. eauto. eauto. eauto. eauto. eauto. eauto.
      eauto. eauto. eauto. eauto. eauto. eauto.
      eapply stp_trans. eauto. eauto. eauto. eauto. eauto. eauto. eauto. reflexivity.
    + SCase "sel2".
      assert (vtpdd m1 G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. subst. inversion H18. omega.
    + SCase "and".
      assert (vtpdd m1 G1 x T6). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T7). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T6). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T7). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd m1 G1 x T7) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.
  - Case "bind".
    inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply vtp_closed1. eauto. eauto.
    + SCase "sel2".
      assert (vtpdd (S m) G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H10. omega.
    + SCase "bind1".
      invty. subst.
      remember (TVar false (length [])) as VZ.
      remember (TVar true x) as VX.

      (* left *)
      assert (vtpd m G1 x (open 0 VX T0)) as LHS. eexists. eassumption.
      euv.
      (* right *)
      assert (substt x (open 0 VZ T0) = (open 0 VX T0)) as R. unfold substt. subst. eapply subst_open_commute0. eauto.
      assert (substt x T3 = T3) as R1. eapply subst_closed_id. eauto.

      assert (vtpdd m G1 x (substt x T3)) as BB. {
        eapply stp_subst_narrowX. rewrite <-R in LHS. eapply LHS.
        instantiate (2:=nil). simpl.
        eapply htp_sub. eapply htp_var. simpl. reflexivity.
        eapply stp_closed1 in H11. simpl in H11. eapply H11. eapply H11. eauto.
        instantiate (1:=nil). simpl. reflexivity. eapply vtp_closed1. eauto. eauto. eauto.
        { intros. eapply IHl. eauto. eauto. omega. eauto. eauto. }
      }
      rewrite R1 in BB.
      euv. repeat eexists. eauto. omega.
    + SCase "bindx".
      invty. subst.
      remember (TVar false (length [])) as VZ.
      remember (TVar true x) as VX.

      (* left *)
      assert (vtpd m G1 x (open 0 VX T0)) as LHS. eexists. eassumption.
      euv.
      (* right *)
      assert (substt x (open 0 VZ T0) = (open 0 VX T0)) as R. unfold substt. subst. eapply subst_open_commute0. eauto.

      assert (vtpdd m G1 x (substt x (open 0 VZ T4))) as BB. {
        eapply stp_subst_narrowX. rewrite <-R in LHS. eapply LHS.
        instantiate (2:=nil). simpl.
        eapply htp_sub. eapply htp_var. simpl. reflexivity.
        eapply stp_closed1 in H11. simpl in H11. eapply H11. eapply H11. eauto.
        instantiate (1:=nil). simpl. reflexivity. eapply vtp_closed1. eauto. eauto. eauto.
        { intros. eapply IHl. eauto. eauto. omega. eauto. eauto. }
      }
      unfold substt in BB. subst. erewrite subst_open_commute0 in BB.
      clear R.
      euv. repeat eexists. eapply vtp_bind. eauto. eauto. omega. eauto. (* enough slack to add bind back *)
    + SCase "and".
      assert (vtpdd (S m) G1 x T1). eapply IHn; eauto. omega. euv.
      assert (vtpdd (S m) G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd (S m) G1 x T1). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd (S m) G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd (S m) G1 x T4) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.
  - Case "ssel2". subst. inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply vtp_closed1. eauto. eauto.
    + SCase "ssel1". index_subst. index_subst. eapply IHn. eapply H6. eauto. eauto. omega. eauto.
    + SCase "ssel2".
      assert (vtpdd m1 G1 x TX0). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel1".
      assert (closed (length ([]:tenv)) (length G1) 0 (TSel (TVar false x0) l1)) as A.
      eapply stpd_closed2. eauto.
      simpl in A. inversion A. inversion H12. omega.
    + SCase "selx".
      eauto.
    + SCase "and".
      assert (vtpdd m1 G1 x T1). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T1). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd m1 G1 x T2) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.
  - Case "and". subst. inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply vtp_closed1. eauto. eauto.
    + SCase "sel2".
      assert (vtpdd m1 G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H13. omega.
    + SCase "and11". eapply IHn in H4. euv. repeat eexists. eauto. omega. eauto. omega. omega. eauto.
    + SCase "and12". eapply IHn in H5. euv. repeat eexists. eauto. omega. eauto. omega. omega. eauto.
    + SCase "and".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "trans".
      assert (vtpdd m1 G1 x T4) as LHS. eapply IHn. eauto. eauto. eauto. omega. eauto. euv.
      assert (vtpdd x0 G1 x T3) as BB. eapply IHn. eapply LHS. eauto. omega. omega. eauto. euv.
      repeat eexists. eauto. omega.

  - Case "or1". subst. inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply vtp_closed1. eauto. eauto.
    + SCase "sel2".
      assert (vtpdd m1 G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H13. omega.
    + SCase "and".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "or...".
      eapply IHn in H4. euv.
      repeat eexists. eapply H4. omega. eauto. omega. omega. eauto.
    + SCase "or...".
      assert (vtpdd m1 G1 x T4) as A. eapply IHn. eapply H. eauto. omega. omega. eauto. euv.
      eapply IHn in A. euv.
      repeat eexists. eauto. omega. eauto. omega. omega. eauto.

  - Case "or2". subst. inversion H0; subst; invty.
    + SCase "top". repeat eexists. eapply vtp_top. eapply vtp_closed1. eauto. eauto.
    + SCase "sel2".
      assert (vtpdd m1 G1 x TX). eapply IHn; eauto. omega.
      euv. repeat eexists. eapply vtp_sel. eauto. eauto. eauto. eauto.
    + SCase "sel2".
      eapply stp_closed2 in H0. simpl in H0. inversion H0. inversion H13. omega.
    + SCase "and".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_and; eauto. eauto.
    + SCase "or1".
      assert (vtpdd m1 G1 x T2). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or1; eauto. eauto.
    + SCase "or2".
      assert (vtpdd m1 G1 x T4). eapply IHn; eauto. omega. euv.
      repeat eexists. eapply vtp_or2; eauto. eauto.
    + SCase "or...".
      eapply IHn in H4. euv.
      repeat eexists. eapply H4. omega. eauto. omega. omega. eauto.
    + SCase "or...".
      assert (vtpdd m1 G1 x T4) as A. eapply IHn. eapply H. eauto. omega. omega. eauto. euv.
      eapply IHn in A. euv.
      repeat eexists. eauto. omega. eauto. omega. omega. eauto.

Grab Existential Variables.
apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.
Qed.

Lemma stp_subst_narrow_z: forall GH0 TX G1 T1 T2 x m n1 n2,
  stp (GH0 ++ [TX]) G1 T1 T2 n2 ->
  vtp m G1 x (substt x TX) n1 ->
  stpd (map (substt x) GH0) G1 (substt x T1) (substt x T2).
Proof.
  intros.
  edestruct stp_subst_narrow0. eauto. eapply vtp_closed1. eauto. eauto.
  { intros. edestruct stp_subst_narrowX. eauto. eauto.
    eapply vtp_closed1. eauto. eauto. eauto.
    { intros. eapply vtp_widen; eauto. }
    ev. repeat eexists. eauto.
  }
  eexists. eassumption.
Qed.

Lemma dms_hastp_inv: forall G1 x ds' T' n,
  dms_has_type [T'] G1 ds' T' n ->
  closed 0 (length G1) 0 (substt x T') ->
  index x G1 = Some (vobj (subst_dms x ds')) ->
  exists m n, vtp m G1 x (substt x T') n.
Proof.
  intros G1 x ds' T' n H HC HI.
  remember T' as T0. remember H as HT0. clear HeqHT0.
  rewrite HeqT0 in H at 2. rewrite HeqT0. rewrite HeqT0 in HC. clear HeqT0.
  remember ds' as ds0. rewrite Heqds0 in H.
  assert (exists dsa, dms_to_list ds0 = dsa ++ dms_to_list ds') as Hds. {
    exists []. rewrite app_nil_l. subst. reflexivity.
  }
  clear Heqds0.
  remember n as n0. rewrite Heqn0 in *. rewrite <- Heqn0 in HT0. clear Heqn0.
  remember [T0] as GH. generalize dependent T0.
  induction H; intros.
  - repeat eexists. eapply vtp_top. eapply index_max. eauto.
  - subst.
    assert (closed 0 (length G1) 0 (substt x TS)) as HCS. {
      unfold substt in *. simpl in HC. inversion HC; subst.
      eauto.
    }
    assert (closed 0 (length G1) 0 (substt x T11)) as HC11. {
      unfold substt in *. simpl in HC. inversion HC; subst.
      inversion H6; subst. eauto.
    }
    assert (stpd [] G1 (substt x T11) (substt x T11)) as A. {
      eapply stpd_refl. eauto.
    }
    eu.
    destruct Hds as [dsa Hdsa]. simpl in Hdsa.
    edestruct IHdms_has_type as [? [? AS]]. eauto. eauto. eauto.
    exists (dsa ++ [dty T11]). rewrite <- app_assoc. simpl. eauto. eauto. eauto.
    unfold substt in *. simpl.
    repeat eexists. eapply vtp_and. eapply vtp_typ. eauto.
    erewrite index_subst_dms with (D:=dty T11). simpl. reflexivity. eauto.
    eauto. eauto. eauto. eauto. eauto.
  - subst.
    assert (closed 0 (length G1) 0 (substt x TS)) as HCS. {
      unfold substt in *. simpl in HC. inversion HC; subst.
      eauto.
    }
    assert (closed 0 (length G1) 0 (substt x T11)) as HC11. {
      unfold substt in *. simpl in HC. inversion HC; subst.
      inversion H10; subst. eauto.
    }
    assert (closed 1 (length G1) 0 (open 0 (TVar false 0) (substt x T12))) as HC12. {
      unfold substt in *. simpl in HC. inversion HC; subst. inversion H10; subst.
      eapply closed_open. eapply closed_upgrade_gh. eauto. omega.
      econstructor. omega.
    }
    assert (stpd [] G1 (substt x T11) (substt x T11)) as A. {
      eapply stpd_refl. eauto.
    }
    eu.
    assert (stpd [(substt x T11)] G1 (open 0 (TVar false 0) (substt x T12)) (open 0 (TVar false 0) (substt x T12))) as B. {
      eapply stpd_refl. eauto.
    }
    eu.
    destruct Hds as [dsa Hdsa]. simpl in Hdsa.
    edestruct IHdms_has_type as [? [? AS]]. eauto. eauto. eauto.
    exists (dsa ++ [dfun OT11 OT12 t12]). rewrite <- app_assoc. simpl. eauto. eauto. eauto.
    unfold substt in *. simpl.
    repeat eexists. eapply vtp_and. eapply vtp_fun. eauto.
    erewrite index_subst_dms with (D:=dfun OT11 OT12 t12). simpl. reflexivity. eauto.
    eapply subst_eq_some; eauto. eapply subst_eq_some; eauto.
    eauto. eapply HT0. simpl. reflexivity. eauto. eauto. eauto. eauto. eauto.
    eauto. eauto. eauto. eauto.
    eapply closed_subst. eauto. econstructor. eapply index_max. eauto.
    eapply closed_subst. eauto. econstructor. eapply index_max. eauto.
    eauto. eauto. eauto. eauto.
Grab Existential Variables.
apply 0. apply 0.
Qed.

Lemma hastp_inv: forall G1 x T n1,
  has_type [] G1 (tvar true x) T n1 ->
  exists m n1, vtp m G1 x T n1.
Proof.
  intros. remember [] as GH. remember (tvar true x) as t.
  induction H; subst; try inversion Heqt.
  - Case "var". subst. eapply dms_hastp_inv; eauto.
  - Case "pack". subst.
    destruct IHhas_type. eauto. eauto. ev.
    repeat eexists. eapply vtp_bind. eauto. eauto.
  - Case "unpack". subst.
    destruct IHhas_type. eauto. eauto. ev. inversion H0.
    repeat eexists. eauto.
  - Case "sub".
    destruct IHhas_type. eauto. eauto. ev.
    assert (exists m0, vtpdd m0 G1 x T2). eexists. eapply vtp_widen; eauto.
    ev. euv. repeat eexists. eauto.
Qed.

Lemma stp_subst_narrow: forall GH0 TX G1 T1 T2 x m n1 n2,
  stp (GH0 ++ [TX]) G1 T1 T2 n2 ->
  vtp m G1 x TX n1 ->
  stpd (map (substt x) GH0) G1 (substt x T1) (substt x T2).
Proof.
  intros. eapply stp_subst_narrow_z. eauto.
  erewrite subst_closed_id. eauto. eapply vtp_closed in H0. eauto.
Qed.

Lemma hastp_subst_aux_z: forall ni, (forall G1 GH TX T x t n1 n2,
  has_type (GH++[TX]) G1 t T n2 -> n2 < ni ->
  has_type [] G1 (tvar true x) (substt x TX) n1 ->
  exists n3, has_type (map (substt x) GH) G1 (subst_tm x t) (substt x T) n3) /\
  (forall G1 GH TX T x ds n1 n2,
  dms_has_type (GH++[TX]) G1 ds T n2 -> n2 < ni ->
  has_type [] G1 (tvar true x) (substt x TX) n1 ->
  exists n3, dms_has_type (map (substt x) GH) G1 (subst_dms x ds) (substt x T) n3).
Proof.
  intro ni. induction ni. split; intros; omega. destruct IHni as [IHniT IHniD].
  split;
  intros; remember (GH++[TX]) as GH0; revert GH HeqGH0; inversion H; intros.
  - Case "vary".
    assert (substt x T = T) as EqT. {
      erewrite subst_closed_id. reflexivity. eauto.
    }
    subst. simpl. eexists. eapply T_Vary. eauto. eauto. eauto.
    rewrite EqT. reflexivity. rewrite EqT. eauto.
  - Case "varz". subst. simpl.
    case_eq (beq_nat x0 0); intros E.
    + assert (x0 = 0). eapply beq_nat_true_iff; eauto. subst x0.
      eapply index_hit0 in H2. subst.
      eapply hastp_upgrade_gh. eauto.
    + assert (x0 <> 0). eapply beq_nat_false_iff; eauto.
      eexists. eapply T_Varz. eapply index_subst1. eauto. eauto.
      rewrite map_length. eapply closed_subst0.
      rewrite app_length in H3. simpl in H3. eapply H3. eapply has_type_closed1. eauto.
  - Case "pack". subst. simpl.
    edestruct IHniT as [? IH]. eauto. omega. eauto.
    assert (substt x (TBind T1) = (TBind (substt x T1))) as A. {
      eauto.
    }
    rewrite A.
    destruct b.
    + eexists. eapply T_VarPack. eapply IH.
      unfold substt. rewrite subst_open_commute1. reflexivity.
      rewrite map_length. eapply closed_subst0. rewrite app_length in H4. simpl in H4.
      apply H4. eapply has_type_closed1. eauto.
    + case_eq (beq_nat x0 0); intros E.
      * assert (x0 = 0). eapply beq_nat_true_iff; eauto. subst x0.
        simpl in IH.
        eexists. eapply T_VarPack. eapply IH. rewrite subst_open_commute0b. eauto.
        rewrite map_length. eapply closed_subst. rewrite app_length in H4. simpl in H4.
        eapply H4. econstructor. eapply has_type_closed1. eauto.
      * assert (x0 <> 0). eapply beq_nat_false_iff; eauto.
        simpl in IH. rewrite E in IH.
        eexists. eapply T_VarPack. eapply IH.
        remember (x0 - 1) as z.
        assert (x0 = z + 1) as B. {
          intuition. destruct x0. specialize (H3 eq_refl). inversion H3.
          subst. simpl. rewrite <- minus_n_O. rewrite NPeano.Nat.add_1_r.
          reflexivity.
        }
        rewrite B. unfold substt.
        rewrite subst_open_commute_z. reflexivity.
        rewrite map_length. eapply closed_subst. rewrite app_length in H4.
        simpl in H4. eapply H4.
        econstructor. eapply has_type_closed1. eauto.
  - Case "unpack". subst. simpl.
    edestruct IHniT as [? IH]. eapply H2. omega. eauto.
    assert (substt x (TBind T1) = (TBind (substt x T1))) as A. {
      eauto.
    }
    rewrite A in IH.
    destruct b.
    + eexists. eapply T_VarUnpack. eapply IH.
      unfold substt. rewrite subst_open_commute1. reflexivity.
      rewrite map_length. eapply closed_subst0. rewrite app_length in H4. simpl in H4.
      apply H4. eapply has_type_closed1. eauto.
    + case_eq (beq_nat x0 0); intros E.
      * assert (x0 = 0). eapply beq_nat_true_iff; eauto. subst x0.
        simpl in IH.
        eexists. eapply T_VarUnpack. eapply IH. rewrite subst_open_commute0b. eauto.
        rewrite map_length. eapply closed_subst. rewrite app_length in H4. simpl in H4.
        eapply H4. econstructor. eapply has_type_closed1. eauto.
      * assert (x0 <> 0). eapply beq_nat_false_iff; eauto.
        simpl in IH. rewrite E in IH.
        eexists. eapply T_VarUnpack. eapply IH.
        remember (x0 - 1) as z.
        assert (x0 = z + 1) as B. {
          intuition. destruct x0. specialize (H3 eq_refl). inversion H3.
          subst. simpl. rewrite <- minus_n_O. rewrite NPeano.Nat.add_1_r.
          reflexivity.
        }
        rewrite B. unfold substt.
        rewrite subst_open_commute_z. reflexivity.
        rewrite map_length. eapply closed_subst. rewrite app_length in H4.
        simpl in H4. eapply H4.
        econstructor. eapply has_type_closed1. eauto.
  - Case "obj".
    edestruct IHniD with (GH:=T'::GH1) as [? IH]. subst. eauto. omega. subst. eauto.
    subst. simpl.
    eexists. eapply T_Obj. eauto.
    rewrite app_length. simpl. unfold substt. rewrite subst_open_commute_z.
    rewrite map_length. eauto.
    eapply closed_subst. rewrite app_length in *. simpl in *. rewrite map_length. eauto.
    econstructor. eapply has_type_closed1. eauto.
  - Case "app". subst. simpl.
    edestruct IHniT as [? IH1]. eapply H2. omega. eauto.
    edestruct IHniT as [? IH2]. eapply H3. omega. eauto.
    eexists. eapply T_App. eauto. eauto. eapply closed_subst.
    subst. rewrite map_length. rewrite app_length in *. simpl in *. eauto.
    subst. rewrite map_length. econstructor. eapply has_type_closed1. eauto.
  - Case "appvar". subst. simpl.
    edestruct IHniT as [? IH1]. eapply H2. omega. eauto.
    edestruct IHniT as [? IH2]. eapply H3. omega. eauto.
    destruct b2.

    eexists. eapply T_AppVar. eauto. eauto.
    rewrite subst_open_commute1. eauto.
    eapply closed_subst. subst. rewrite map_length. rewrite app_length in *. simpl in *.
    eapply closed_upgrade_gh. eassumption. omega.
    subst. rewrite map_length. econstructor. eapply has_type_closed1. eauto.

    case_eq (beq_nat x2 0); intros E.

    eapply beq_nat_true in E. subst.
    rewrite subst_open_commute0b.
    eexists. eapply T_AppVar. eauto. eauto. eauto.
    rewrite map_length. rewrite <- subst_open_commute0b.
    eapply closed_subst. eapply closed_upgrade_gh. eassumption.
    rewrite app_length. simpl. omega.
    econstructor. eapply has_type_closed1. eauto.

    rewrite subst_open5.
    simpl in *. rewrite E in *.
    eexists. eapply T_AppVar. eauto. eauto. eauto.
    rewrite <- subst_open5. eapply closed_subst.
    subst. rewrite map_length. rewrite app_length in *. simpl in *. eassumption.
    subst. rewrite map_length. econstructor. eapply has_type_closed1. eauto.
    apply []. apply beq_nat_false. apply E. apply []. apply beq_nat_false. apply E.
  - Case "sub". subst.
    edestruct hastp_inv as [? [? HV]]; eauto.
    edestruct stp_subst_narrow_z. eapply H3. eapply HV.
    edestruct IHniT as [? IH]. eapply H2. omega. eauto.
    eexists. eapply T_Sub. eauto. eauto.
  - Case "dnil". subst. simpl.
    eexists. eapply D_Nil.
  - Case "typ". subst. simpl.
    edestruct IHniD as [? IH]. eapply H2. omega. eauto.
    eexists. eapply D_Typ. eauto. eapply closed_subst0.
    rewrite app_length in H3. rewrite map_length. eauto.
    eapply has_type_closed1. eauto. eauto.
    unfold substt. simpl. rewrite <- length_subst_dms. reflexivity.
  - Case "abs". subst. simpl.
    edestruct IHniD as [? IHD]. eapply H2. omega. eauto.
    edestruct IHniT with (GH:=T11::GH1) as [? HI] . eauto. omega. eauto.
    simpl in HI.
    eexists. eapply D_Fun. eapply IHD. eapply HI.
    rewrite map_length. rewrite app_length. simpl.
    rewrite subst_open. unfold substt. reflexivity.
    eapply closed_subst0. rewrite map_length.
    rewrite app_length in H5. simpl in H5. eauto. eauto.
    eapply has_type_closed1. eauto.
    eapply closed_subst0. rewrite map_length.
    rewrite app_length in H6. simpl in H6. eauto.
    eapply has_type_closed1. eauto. eauto.
    unfold substt. simpl. rewrite <- length_subst_dms. reflexivity.
    eapply subst_eq_some; eauto. eapply subst_eq_some; eauto.
Grab Existential Variables.
apply 0. apply 0.
Qed.

Lemma hastp_subst_z: forall G1 GH TX T x t n1 n2,
  has_type (GH++[TX]) G1 t T n2 ->
  has_type [] G1 (tvar true x) (substt x TX) n1 ->
  exists n3, has_type (map (substt x) GH) G1 (subst_tm x t) (substt x T) n3.
Proof.
  intros. eapply hastp_subst_aux_z with (t:=t). eauto. eauto. eauto.
Qed.

Lemma hastp_subst: forall G1 GH TX T x t n1 n2,
  has_type (GH++[TX]) G1 t T n2 ->
  has_type [] G1 (tvar true x) TX n1 ->
  exists n3, has_type (map (substt x) GH) G1 (subst_tm x t) (substt x T) n3.
Proof.
  intros. eapply hastp_subst_z with (t:=t). eauto.
  erewrite subst_closed_id. eauto. eapply has_type_closed in H0. eauto.
Qed.

Theorem type_safety : forall G t T n1,
  has_type [] G t T n1 ->
  (exists x, t = tvar true x /\ (exists ds, index x G = Some ds)) \/
  (exists G' t' n2, step G t (G'++G) t' /\ has_type [] (G'++G) t' T n2).
Proof.
  intros.
  assert (closed (length ([]:tenv)) (length G) 0 T) as CL. eapply has_type_closed. eauto.
  remember [] as GH. remember t as tt. remember T as TT.
  revert T t HeqTT HeqGH Heqtt CL.
  induction H; intros.
  - Case "vary". eauto.
  - Case "varz". subst GH. inversion H.
  - Case "pack". subst GH.
    eapply has_type_closed_b in H. destruct H. subst.
    left. eexists. split. reflexivity. eapply index_exists. assumption.
  - Case "unpack". subst GH.
    eapply has_type_closed_b in H. destruct H. subst.
    left. eexists. split. reflexivity. eapply index_exists. assumption.
  - Case "obj". subst. right.
    repeat eexists. rewrite <- app_cons1. eapply ST_Obj.
    eapply T_VarPack. eapply T_Vary.
    simpl. rewrite beq_nat_true_eq. eauto. eapply dms_has_type_extend. eauto. eauto. eauto.
    eapply closed_subst. eapply closed_open. eapply closed_extend. eapply closed_upgrade_gh. eauto.
    simpl. omega. simpl. econstructor. omega. simpl. econstructor. omega.
    simpl. rewrite subst_open_commute0b. erewrite subst_closed_id. reflexivity. eauto.
    eapply closed_extend. eauto.
  - Case "app". subst.
    assert (closed (length ([]:tenv)) (length G1) 0 (TFun l T1 T)) as TF. eapply has_type_closed. eauto.
    assert ((exists x : id, t2 = tvar true x /\ (exists ds, index x G1 = Some ds)) \/
                (exists (G' : venv) (t' : tm) n2,
                   step G1 t2 (G'++G1) t' /\ has_type [] (G'++G1) t' T1 n2)) as HX.
    eapply IHhas_type2. eauto. eauto. eauto. inversion TF. eauto.
    assert ((exists x : id, t1 = tvar true x /\ (exists ds, index x G1 = Some ds)) \/
                (exists (G' : venv) (t' : tm) n2,
                   step G1 t1 (G'++G1) t' /\ has_type [] (G'++G1) t' (TFun l T1 T) n2)) as HF.
    eapply IHhas_type1. eauto. eauto. eauto. eauto.
    destruct HF.
    + SCase "fun-val".
      destruct HX as [HX | HX].
      * SSCase "arg-val".
        ev. subst.
        assert (exists m n1, vtp m G1 x (TFun l T1 T) n1). eapply hastp_inv. eauto.
        assert (exists m n1, vtp m G1 x0 T1 n1). eapply hastp_inv. eauto.
        ev. inversion H2. subst.
        remember (substt x T1x) as T0. remember (substt x T2x) as T2.
        assert (vtpdd x3 G1 x0 T0). eapply vtp_widen. eauto. eauto. eauto. eauto. eauto.
        euv.
        assert (exists T, (exists n1, has_type [] G1 (tvar true x) T n1) /\ substt x T' = T) as A. {
          eexists. split. eexists. eapply T_Vary. eauto. eauto. eauto. eauto.
          eapply closed_subst. eapply dms_has_type_closed in H14. eauto. econstructor.
          eapply index_max in H9. omega. reflexivity.
        }
        destruct A as [Tx [[na A] EqTx]].
        assert (has_typed (map (substt x) [T1x]) G1 (subst_tm x tx) (substt x (open 0 (TVar false 1) T2x))) as HIx.
        eapply hastp_subst_z. eapply H21. rewrite EqTx. eapply A.
        eu. simpl in HIx.
        assert (has_typed (map (substt x0) []) G1
                          (subst_tm x0 (subst_tm x tx))
                          (substt x0 (substt x (open 0 (TVar false 1) T2x)))) as HIx0. {
          eapply hastp_subst. rewrite app_nil_l. eapply HIx.
          rewrite <- HeqT0. eauto.
        }
        eu. simpl in HIx0.
        assert ((substt x (open 0 (TVar false 1) T2x))=(open 0 (TVar false 0) (substt x T2x))) as EqT2x. {
          change 1 with (0+1). rewrite subst_open. reflexivity.
        }
        assert (has_typed [] G1 (subst_tm x0 t) (substt x0 (open 0 (TVar false 0) T2))) as HI. {
          inversion H15; subst. rewrite <- EqT2x. eexists. eapply HIx0.
        }
        eu. simpl in HI.
        edestruct stp_subst_narrow as [? HI2]. rewrite app_nil_l. eapply H31. eauto.
        simpl in HI2.
        assert (substt x0 (open 0 (TVar false 0) T) = T) as EqT. {
          erewrite <- closed_no_open. erewrite subst_closed_id. reflexivity.
          eassumption. eassumption.
        }
        rewrite EqT in HI2.
        right. repeat eexists. rewrite app_nil_l. eapply ST_AppAbs. eauto. eauto.
        eapply T_Sub. eauto. eauto.
      * SSCase "arg_step".
        ev. subst.
        right. repeat eexists. eapply ST_App2. eauto. eapply T_App.
        eapply has_type_extend_mult. eauto. eauto.
        simpl in *. rewrite app_length. eapply closed_extend_mult. eassumption. omega.
    + SCase "fun_step".
      ev. subst. right. repeat eexists. eapply ST_App1. eauto. eapply T_App.
      eauto. eapply has_type_extend_mult. eauto.
      simpl in *. rewrite app_length. eapply closed_extend_mult. eassumption. omega.

  - Case "appvar". subst.
    assert (closed (length ([]:tenv)) (length G1) 0 (TFun l T1 T2)) as TF. eapply has_type_closed. eauto.
    assert ((exists x : id, tvar b2 x2 = tvar true x /\ (exists ds, index x G1 = Some ds)) \/
                (exists (G' : venv) (t' : tm) n2,
                   step G1 (tvar b2 x2) (G'++G1) t' /\ has_type [] (G'++G1) t' T1 n2)) as HX.
    eapply IHhas_type2. eauto. eauto. eauto. inversion TF. eauto.
    assert (b2 = true) as HXeq. {
      destruct HX as [[? HX] | Contra]. destruct HX as [HX1 HX2]. inversion HX1. reflexivity.
      destruct Contra as [G' [t' [n' [Hstep Htyp]]]].
      inversion Hstep.
    }
    clear HX. subst b2.
    assert ((exists x : id, t1 = tvar true x /\ (exists ds, index x G1 = Some ds)) \/
                (exists (G' : venv) (t' : tm) n2,
                   step G1 t1 (G'++G1) t' /\ has_type [] (G'++G1) t' (TFun l T1 T2) n2)) as HF.
    eapply IHhas_type1. eauto. eauto. eauto. eauto.
    destruct HF as [HF | HF].
    + SCase "fun-val".
      ev. subst.
      assert (exists m n1, vtp m G1 x (TFun l T1 T2) n1). eapply hastp_inv. eauto.
      assert (exists m n1, vtp m G1 x2 T1 n1). eapply hastp_inv. eauto.
      ev. inversion H1. subst.
      remember (substt x T1x) as T0. remember (substt x T2x) as T3.
      assert (vtpdd x1 G1 x2 T0). eapply vtp_widen. eauto. eauto. eauto. eauto. eauto.
      euv.
      assert (exists T, (exists n1, has_type [] G1 (tvar true x) T n1) /\ substt x T' = T) as A. {
        eexists. split. eexists. eapply T_Vary. eauto. eauto. eauto. eauto.
        eapply closed_subst. eapply dms_has_type_closed in H13. eauto. econstructor.
        eapply index_max in H8. omega. reflexivity.
      }
      destruct A as [Tx [[na A] EqTx]].
      assert (has_typed (map (substt x) [T1x]) G1 (subst_tm x tx) (substt x (open 0 (TVar false 1) T2x))) as HIx.
      eapply hastp_subst_z. eapply H20. rewrite EqTx. eapply A.
      eu. simpl in HIx.
      assert (has_typed (map (substt x2) []) G1
                        (subst_tm x2 (subst_tm x tx))
                        (substt x2 (substt x (open 0 (TVar false 1) T2x)))) as HIx0. {
        eapply hastp_subst. rewrite app_nil_l. eapply HIx.
        rewrite <- HeqT0. eauto.
      }
      eu. simpl in HIx0.
      assert ((substt x (open 0 (TVar false 1) T2x))=(open 0 (TVar false 0) (substt x T2x))) as EqT2x. {
        change 1 with (0+1). rewrite subst_open. reflexivity.
      }
      assert (has_typed [] G1 (subst_tm x2 t) (substt x2 (open 0 (TVar false 0) T3))) as HI. {
        inversion H14; subst. rewrite <- EqT2x. eauto.
      }
      eu. simpl in HI.
      edestruct stp_subst_narrow as [? HI2]. rewrite app_nil_l. eapply H30. eauto.
      simpl in HI2.
      assert ((substt x2 (open 0 (TVar false 0) T2))=(open 0 (TVar true x2) T2)) as EqT2. {
        rewrite subst_open_commute0b. erewrite subst_closed_id. reflexivity.
        eassumption.
      }
      rewrite EqT2 in HI2.
      right. repeat eexists. rewrite app_nil_l. eapply ST_AppAbs. eauto. eauto.
      eapply T_Sub. eauto. eauto.
    + SCase "fun_step".
      ev. subst. right. repeat eexists. eapply ST_App1. eauto. eapply T_AppVar.
      eauto. eapply has_type_extend_mult. eauto. reflexivity.
      simpl in *. rewrite app_length. eapply closed_extend_mult. eassumption. omega.

  - Case "sub". subst.
    assert ((exists x : id, t0 = tvar true x /\ (exists ds, index x G1 = Some ds)) \/
               (exists (G' : venv) (t' : tm) n2,
                  step G1 t0 (G'++G1) t' /\ has_type [] (G'++G1) t' T1 n2)) as HH.
    eapply IHhas_type; eauto. change 0 with (length ([]:tenv)) at 1. eapply stpd_closed1; eauto.
    destruct HH.
    + SCase "val".
      ev. subst. left. eexists. eauto.
    + SCase "step".
      ev. subst.
      right. repeat eexists. eauto. eapply T_Sub. eauto. eapply stp_extend_mult. eauto.
Qed.


Require Export SystemFR.TreeLists.
Require Export SystemFR.ErasedTermLemmas.

Require Import PeanoNat.

Open Scope list_scope.

Lemma subst_erased:
  forall t l tag,
    is_erased_term t ->
    erased_terms l ->
    is_erased_term (psubstitute t l tag).
Proof.
  induction t; steps; eauto using erased_term_in_list.
Qed.

#[export]
Hint Resolve subst_erased: erased.

Lemma subst_erased_type:
  forall t l,
    is_erased_type t ->
    erased_terms l ->
    is_erased_type (psubstitute t l term_var).
Proof.
  induction t; steps;
    eauto using subst_erased;
    eauto using erased_term_in_list.
Qed.

#[export]
Hint Resolve subst_erased_type: erased.

Lemma subst_erased_type2:
  forall T X V,
    is_erased_type T ->
    is_erased_type V ->
    is_erased_type (psubstitute T ((X,V) :: nil) type_var).
Proof.
  induction T; repeat step || rewrite is_erased_subst;
    eauto using subst_erased.
Qed.

#[export]
Hint Resolve subst_erased_type2: erased.


(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below    *)
Require Import BuiltIn.
Require BuiltIn.
Require int.Int.
Require int.Abs.
Require int.EuclideanDivision.
Require int.ComputerDivision.
Require number.Parity.
Require number.Divisibility.
Require number.Prime.
Require map.Map.

(* Why3 assumption *)
Definition unit := unit.

Axiom qtmark : Type.
Parameter qtmark_WhyType : WhyType qtmark.
Existing Instance qtmark_WhyType.

(* Why3 assumption *)
Definition lt_nat (x:Z) (y:Z): Prop := (0%Z <= y)%Z /\ (x < y)%Z.

(* Why3 assumption *)
Inductive lex: (Z* Z)%type -> (Z* Z)%type -> Prop :=
  | Lex_1 : forall (x1:Z) (x2:Z) (y1:Z) (y2:Z), (lt_nat x1 x2) -> (lex (x1,
      y1) (x2, y2))
  | Lex_2 : forall (x:Z) (y1:Z) (y2:Z), (lt_nat y1 y2) -> (lex (x, y1) (x,
      y2)).

(* Why3 assumption *)
Inductive ref (a:Type) :=
  | mk_ref : a -> ref a.
Axiom ref_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (ref a).
Existing Instance ref_WhyType.
Implicit Arguments mk_ref [[a]].

(* Why3 assumption *)
Definition contents {a:Type} {a_WT:WhyType a} (v:(ref a)): a :=
  match v with
  | (mk_ref x) => x
  end.

(* Why3 assumption *)
Inductive array (a:Type) :=
  | mk_array : Z -> (map.Map.map Z a) -> array a.
Axiom array_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (array a).
Existing Instance array_WhyType.
Implicit Arguments mk_array [[a]].

(* Why3 assumption *)
Definition elts {a:Type} {a_WT:WhyType a} (v:(array a)): (map.Map.map Z a) :=
  match v with
  | (mk_array x x1) => x1
  end.

(* Why3 assumption *)
Definition length {a:Type} {a_WT:WhyType a} (v:(array a)): Z :=
  match v with
  | (mk_array x x1) => x
  end.

(* Why3 assumption *)
Definition get {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z): a :=
  (map.Map.get (elts a1) i).

(* Why3 assumption *)
Definition set {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z) (v:a): (array
  a) := (mk_array (length a1) (map.Map.set (elts a1) i v)).

(* Why3 assumption *)
Definition no_prime_in (l:Z) (u:Z): Prop := forall (x:Z), ((l < x)%Z /\
  (x < u)%Z) -> ~ (number.Prime.prime x).

(* Why3 assumption *)
Definition first_primes (p:(array Z)) (u:Z): Prop := ((get p 0%Z) = 2%Z) /\
  ((forall (i:Z) (j:Z), ((0%Z <= i)%Z /\ ((i < j)%Z /\ (j < u)%Z)) -> ((get p
  i) < (get p j))%Z) /\ ((forall (i:Z), ((0%Z <= i)%Z /\ (i < u)%Z) ->
  (number.Prime.prime (get p i))) /\ forall (i:Z), ((0%Z <= i)%Z /\
  (i < (u - 1%Z)%Z)%Z) -> (no_prime_in (get p i) (get p (i + 1%Z)%Z)))).

Axiom exists_prime : forall (p:(array Z)) (u:Z), (1%Z <= u)%Z ->
  ((first_primes p u) -> forall (d:Z), ((2%Z <= d)%Z /\ (d <= (get p
  (u - 1%Z)%Z))%Z) -> ((number.Prime.prime d) -> exists i:Z, ((0%Z <= i)%Z /\
  (i < u)%Z) /\ (d = (get p i)))).

Axiom Bertrand_postulate : forall (p:Z), (number.Prime.prime p) ->
  ~ (no_prime_in p (2%Z * p)%Z).

(* Why3 goal *)
Theorem WP_parameter_prime_numbers : forall (m:Z), (2%Z <= m)%Z ->
  ((0%Z <= m)%Z -> forall (p:Z) (p1:(map.Map.map Z Z)), ((0%Z <= p)%Z /\
  ((p = m) /\ forall (i:Z), ((0%Z <= i)%Z /\ (i < m)%Z) -> ((map.Map.get p1
  i) = 0%Z))) -> (((0%Z <= 0%Z)%Z /\ (0%Z < p)%Z) -> forall (p2:(map.Map.map
  Z Z)), ((0%Z <= p)%Z /\ (p2 = (map.Map.set p1 0%Z 2%Z))) ->
  (((0%Z <= 1%Z)%Z /\ (1%Z < p)%Z) -> forall (p3:(map.Map.map Z Z)),
  ((0%Z <= p)%Z /\ (p3 = (map.Map.set p2 1%Z 3%Z))) -> let o :=
  (m - 1%Z)%Z in ((2%Z <= o)%Z -> forall (n:Z) (p4:(map.Map.map Z Z)),
  forall (j:Z), ((2%Z <= j)%Z /\ (j <= o)%Z) -> (((first_primes (mk_array p
  p4) j) /\ ((((map.Map.get p4 (j - 1%Z)%Z) < n)%Z /\
  (n < (2%Z * (map.Map.get p4 (j - 1%Z)%Z))%Z)%Z) /\ ((number.Parity.odd
  n) /\ (no_prime_in (map.Map.get p4 (j - 1%Z)%Z) n)))) -> forall (k:Z),
  forall (n1:Z) (p5:(map.Map.map Z Z)), ((0%Z <= p)%Z /\ (((1%Z <= k)%Z /\
  (k < j)%Z) /\ ((first_primes (mk_array p p5) j) /\ ((((map.Map.get p5
  (j - 1%Z)%Z) < n1)%Z /\ (n1 < (2%Z * (map.Map.get p5 (j - 1%Z)%Z))%Z)%Z) /\
  ((number.Parity.odd n1) /\ ((no_prime_in (map.Map.get p5 (j - 1%Z)%Z)
  n1) /\ forall (i:Z), ((0%Z <= i)%Z /\ (i < k)%Z) ->
  ~ (number.Divisibility.divides (map.Map.get p5 i) n1))))))) ->
  (((0%Z <= k)%Z /\ (k < p)%Z) -> (((ZArith.BinInt.Z.rem n1 (map.Map.get p5
  k)) = 0%Z) -> ~ (number.Prime.prime n1)))))))).
intros m h1 h2 p p1 (h3,(h4,h5)) (h6,h7) p2 (h8,h9) (h10,h11) p3 (h12,h13) o
h14 n p4 j (h15,h16) (h17,((h18,h19),(h20,h21))) k n1 p5
(h22,((h23,h24),(h25,((h26,h27),(h28,(h29,h30)))))) (h31,h32) h33.
(*
intros m h1 h2 h3 (h4,h5) p (h6,h7) (h8,h9) p1 (h10,h11) o h12 n p2 j
        (h13,h14) (h15,((h16,h17),(h18,h19))) k n1 p3
        (h20,((h21,h22),(h23,((h24,h25),(h26,(h27,h28)))))) (h29,h30) h31.
*)
intro h0.
intuition.
red in h0. destruct h0.
red in h25. decompose [and] h25. clear h25.
apply H0 with (Map.get p5 k).
assert (2 < Map.get p5 k)%Z.
rewrite <- H1.
apply H3; omega.
split. omega.
assert (case: (k<j-1 \/ k=j-1)%Z) by omega. destruct case.
apply Zlt_trans with (Map.get p5 (j-1))%Z; try omega.
apply H3; omega.
subst k; auto.
apply Divisibility.mod_divides_computer; auto.
assert (2 < Map.get p5 k)%Z.
rewrite <- H1.
apply H3; omega.
omega.
Qed.


From iris.base_logic Require Export base_logic.
From iris.algebra Require Import gmap.
From iris.algebra Require cofe_solver.
Set Default Proof Using "Type".

(** In this file we construct the type [iProp] of propositions of the Iris
logic. This is done by solving the following recursive domain equation:

  iProp ≈ uPred (∀ i : gid, gname -fin-> (Σ i) iProp)

where:

  Σ : gFunctors  := lists of locally constractive functors
  i : gid        := indexes addressing individual functors in [Σ]
  γ : gname      := ghost variable names

The Iris logic is parametrized by a list of locally contractive functors [Σ]
from the category of COFEs to the category of CMRAs. These functors are
instantiated with [iProp], the type of Iris propositions, which allows one to
construct impredicate CMRAs, such as invariants and stored propositions using
the agreement CMRA. *)

(** * Locally contractive functors *)
(** The type [gFunctor] bundles a functor from the category of COFEs to the
category of CMRAs with a proof that it is locally contractive. *)
Structure gFunctor := GFunctor {
  gFunctor_F :> rFunctor;
  gFunctor_contractive : rFunctorContractive gFunctor_F;
}.
Arguments GFunctor _ {_}.
Existing Instance gFunctor_contractive.

(** The type [gFunctors] describes the parameters [Σ] of the Iris logic: lists
of [gFunctor]s.

Note that [gFunctors] is isomorphic to [list gFunctor], but defined in an
alternative way to avoid universe inconsistencies with respect to the universe
monomorphic [list] type. *)
Definition gFunctors := { n : nat & fin n → gFunctor }.

Definition gid (Σ : gFunctors) := fin (projT1 Σ).
Definition gFunctors_lookup (Σ : gFunctors) : gid Σ → gFunctor := projT2 Σ.
Coercion gFunctors_lookup : gFunctors >-> Funclass.

Definition gname := positive.

(** The resources functor [iResF Σ A := ∀ i : gid, gname -fin-> (Σ i) A]. *)
Definition iResF (Σ : gFunctors) : urFunctor :=
  ofe_funURF (λ i, gmapURF gname (Σ i)).

(** We define functions for the empty list of functors, the singleton list of
functors, and the append operator on lists of functors. These are used to
compose [gFunctors] out of smaller pieces. *)
Module gFunctors.
  Definition nil : gFunctors := existT 0 (fin_0_inv _).

  Definition singleton (F : gFunctor) : gFunctors :=
    existT 1 (fin_S_inv (λ _, gFunctor) F (fin_0_inv _)).

  Definition app (Σ1 Σ2 : gFunctors) : gFunctors :=
    existT (projT1 Σ1 + projT1 Σ2) (fin_plus_inv _ (projT2 Σ1) (projT2 Σ2)).
End gFunctors.

Coercion gFunctors.singleton : gFunctor >-> gFunctors.
Notation "#[ ]" := gFunctors.nil (format "#[ ]").
Notation "#[ Σ1 ; .. ; Σn ]" :=
  (gFunctors.app Σ1 .. (gFunctors.app Σn gFunctors.nil) ..).

(** * Subfunctors *)
(** In order to make proofs in the Iris logic modular, they are not done with
respect to some concrete list of functors [Σ], but are instead parametrized by
an arbitrary list of functors [Σ] that contains at least certain functors. For
example, the lock library is parameterized by a functor [Σ] that should have
the functors corresponding to the heap and the exclusive monoid to manage to
lock invariant.

The contraints to can be expressed using the type class [subG Σ1 Σ2], which
expresses that the functors [Σ1] are contained in [Σ2]. *)
Class subG (Σ1 Σ2 : gFunctors) := in_subG i : { j | Σ1 i = Σ2 j }.

(** Avoid trigger happy type class search: this line ensures that type class
search is only triggered if the arguments of [subG] do not contain evars. Since
instance search for [subG] is restrained, instances should persistently have [subG] as
their first parameter to avoid loops. For example, the instances [subG_authΣ]
and [auth_discrete] otherwise create a cycle that pops up arbitrarily. *)
Hint Mode subG + + : typeclass_instances.

Lemma subG_inv Σ1 Σ2 Σ : subG (gFunctors.app Σ1 Σ2) Σ → subG Σ1 Σ * subG Σ2 Σ.
Proof.
  move=> H; split.
  - move=> i; move: H=> /(_ (Fin.L _ i)) [j] /=. rewrite fin_plus_inv_L; eauto.
  - move=> i; move: H=> /(_ (Fin.R _ i)) [j] /=. rewrite fin_plus_inv_R; eauto.
Qed.

Instance subG_refl Σ : subG Σ Σ.
Proof. move=> i; by exists i. Qed.
Instance subG_app_l Σ Σ1 Σ2 : subG Σ Σ1 → subG Σ (gFunctors.app Σ1 Σ2).
Proof.
  move=> H i; move: H=> /(_ i) [j ?].
  exists (Fin.L _ j). by rewrite /= fin_plus_inv_L.
Qed.
Instance subG_app_r Σ Σ1 Σ2 : subG Σ Σ2 → subG Σ (gFunctors.app Σ1 Σ2).
Proof.
  move=> H i; move: H=> /(_ i) [j ?].
  exists (Fin.R _ j). by rewrite /= fin_plus_inv_R.
Qed.

(** * Solution of the recursive domain equation *)
(** We first declare a module type and then an instance of it so as to seal all of
the construction, this way we are sure we do not use any properties of the
construction, and also avoid Coq from blindly unfolding it. *)
Module Type iProp_solution_sig.
  Parameter iPreProp : gFunctors → ofeT.
  Definition iResUR (Σ : gFunctors) : ucmraT :=
    ofe_funUR (λ i, gmapUR gname (Σ i (iPreProp Σ))).
  Notation iProp Σ := (uPredC (iResUR Σ)).
  Notation iPropI Σ := (uPredI (iResUR Σ)).
  Notation iPropSI Σ := (uPredSI (iResUR Σ)).

  Parameter iProp_unfold: ∀ {Σ}, iProp Σ -n> iPreProp Σ.
  Parameter iProp_fold: ∀ {Σ}, iPreProp Σ -n> iProp Σ.
  Parameter iProp_fold_unfold: ∀ {Σ} (P : iProp Σ),
    iProp_fold (iProp_unfold P) ≡ P.
  Parameter iProp_unfold_fold: ∀ {Σ} (P : iPreProp Σ),
    iProp_unfold (iProp_fold P) ≡ P.
End iProp_solution_sig.

Module Export iProp_solution : iProp_solution_sig.
  Import cofe_solver.
  Definition iProp_result (Σ : gFunctors) :
    solution (uPredCF (iResF Σ)) := solver.result _.

  Definition iPreProp (Σ : gFunctors) : ofeT := iProp_result Σ.
  Definition iResUR (Σ : gFunctors) : ucmraT :=
    ofe_funUR (λ i, gmapUR gname (Σ i (iPreProp Σ))).
  Notation iProp Σ := (uPredC (iResUR Σ)).

  Definition iProp_unfold {Σ} : iProp Σ -n> iPreProp Σ :=
    solution_fold (iProp_result Σ).
  Definition iProp_fold {Σ} : iPreProp Σ -n> iProp Σ := solution_unfold _.
  Lemma iProp_fold_unfold {Σ} (P : iProp Σ) : iProp_fold (iProp_unfold P) ≡ P.
  Proof. apply solution_unfold_fold. Qed.
  Lemma iProp_unfold_fold {Σ} (P : iPreProp Σ) : iProp_unfold (iProp_fold P) ≡ P.
  Proof. apply solution_fold_unfold. Qed.
End iProp_solution.

(** * Properties of the solution to the recursive domain equation *)
Lemma iProp_unfold_equivI {Σ} (P Q : iProp Σ) :
  iProp_unfold P ≡ iProp_unfold Q ⊢@{iPropI Σ} P ≡ Q.
Proof.
  rewrite -{2}(iProp_fold_unfold P) -{2}(iProp_fold_unfold Q). apply: bi.f_equiv.
Qed.