(** * Norm: Normalization of STLC *)

(* Chapter maintained by Andrew Tolmach *)

(* (Based on TAPL Ch. 12.) *)

Require Export Smallstep.
Hint Constructors multi.

(**
(This chapter is optional.)

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

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

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

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

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

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

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

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

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

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

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

Inductive tm : Type :=
    (* pure STLC *)
  | tvar : id -> tm
  | tapp : tm -> tm -> tm
  | tabs : id -> ty -> tm -> tm
    (* pairs *)
  | tpair : tm -> tm -> tm
  | tfst : tm -> tm
  | tsnd : tm -> tm
    (* booleans *)
  | ttrue : tm
  | tfalse : tm
  | tif : tm -> tm -> tm -> tm.
          (* i.e., [if t0 then t1 else t2] *)

Tactic Notation "t_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "tvar" | Case_aux c "tapp" | Case_aux c "tabs"
  | Case_aux c "tpair" | Case_aux c "tfst" | Case_aux c "tsnd"
  | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ].

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

Fixpoint subst (x:id) (s:tm) (t:tm) : tm :=
  match t with
  | tvar y => if eq_id_dec x y then s else t
  | tabs y T t1 =>  tabs y T (if eq_id_dec x y then t1 else (subst x s t1))
  | tapp t1 t2 => tapp (subst x s t1) (subst x s t2)
  | tpair t1 t2 => tpair (subst x s t1) (subst x s t2)
  | tfst t1 => tfst (subst x s t1)
  | tsnd t1 => tsnd (subst x s t1)
  | ttrue => ttrue
  | tfalse => tfalse
  | tif t0 t1 t2 => tif (subst x s t0) (subst x s t1) (subst x s t2)
  end.

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

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

Inductive value : tm -> Prop :=
  | v_abs : forall x T11 t12,
      value (tabs x T11 t12)
  | v_pair : forall v1 v2,
      value v1 ->
      value v2 ->
      value (tpair v1 v2)
  | v_true : value ttrue
  | v_false : value tfalse
.

Hint Constructors value.

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

Inductive step : tm -> tm -> Prop :=
  | ST_AppAbs : forall x T11 t12 v2,
         value v2 ->
         (tapp (tabs x T11 t12) v2) ==> [x:=v2]t12
  | ST_App1 : forall t1 t1' t2,
         t1 ==> t1' ->
         (tapp t1 t2) ==> (tapp t1' t2)
  | ST_App2 : forall v1 t2 t2',
         value v1 ->
         t2 ==> t2' ->
         (tapp v1 t2) ==> (tapp v1 t2')
  (* pairs *)
  | ST_Pair1 : forall t1 t1' t2,
        t1 ==> t1' ->
        (tpair t1 t2) ==> (tpair t1' t2)
  | ST_Pair2 : forall v1 t2 t2',
        value v1 ->
        t2 ==> t2' ->
        (tpair v1 t2) ==> (tpair v1 t2')
  | ST_Fst : forall t1 t1',
        t1 ==> t1' ->
        (tfst t1) ==> (tfst t1')
  | ST_FstPair : forall v1 v2,
        value v1 ->
        value v2 ->
        (tfst (tpair v1 v2)) ==> v1
  | ST_Snd : forall t1 t1',
        t1 ==> t1' ->
        (tsnd t1) ==> (tsnd t1')
  | ST_SndPair : forall v1 v2,
        value v1 ->
        value v2 ->
        (tsnd (tpair v1 v2)) ==> v2
  (* booleans *)
  | ST_IfTrue : forall t1 t2,
        (tif ttrue t1 t2) ==> t1
  | ST_IfFalse : forall t1 t2,
        (tif tfalse t1 t2) ==> t2
  | ST_If : forall t0 t0' t1 t2,
        t0 ==> t0' ->
        (tif t0 t1 t2) ==> (tif t0' t1 t2)

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

Tactic Notation "step_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "ST_AppAbs" | Case_aux c "ST_App1" | Case_aux c "ST_App2"
  | Case_aux c "ST_Pair1" | Case_aux c "ST_Pair2"
    | Case_aux c "ST_Fst" | Case_aux c "ST_FstPair"
    | Case_aux c "ST_Snd" | Case_aux c "ST_SndPair"
  | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].

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

Hint Constructors step.

Notation step_normal_form := (normal_form step).

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

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

Definition context := partial_map ty.

Inductive has_type : context -> tm -> ty -> Prop :=
  (* Typing rules for proper terms *)
  | T_Var : forall Gamma x T,
      Gamma x = Some T ->
      has_type Gamma (tvar x) T
  | T_Abs : forall Gamma x T11 T12 t12,
      has_type (extend Gamma x T11) t12 T12 ->
      has_type Gamma (tabs x T11 t12) (TArrow T11 T12)
  | T_App : forall T1 T2 Gamma t1 t2,
      has_type Gamma t1 (TArrow T1 T2) ->
      has_type Gamma t2 T1 ->
      has_type Gamma (tapp t1 t2) T2
  (* pairs *)
  | T_Pair : forall Gamma t1 t2 T1 T2,
      has_type Gamma t1 T1 ->
      has_type Gamma t2 T2 ->
      has_type Gamma (tpair t1 t2) (TProd T1 T2)
  | T_Fst : forall Gamma t T1 T2,
      has_type Gamma t (TProd T1 T2) ->
      has_type Gamma (tfst t) T1
  | T_Snd : forall Gamma t T1 T2,
      has_type Gamma t (TProd T1 T2) ->
      has_type Gamma (tsnd t) T2
  (* booleans *)
  | T_True : forall Gamma,
      has_type Gamma ttrue TBool
  | T_False : forall Gamma,
      has_type Gamma tfalse TBool
  | T_If : forall Gamma t0 t1 t2 T,
      has_type Gamma t0 TBool ->
      has_type Gamma t1 T ->
      has_type Gamma t2 T ->
      has_type Gamma (tif t0 t1 t2) T
.

Hint Constructors has_type.

Tactic Notation "has_type_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "T_Var" | Case_aux c "T_Abs" | Case_aux c "T_App"
  | Case_aux c "T_Pair" | Case_aux c "T_Fst" | Case_aux c "T_Snd"
  | Case_aux c "T_True" | Case_aux c "T_False" | Case_aux c "T_If" ].

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

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

Inductive appears_free_in : id -> tm -> Prop :=
  | afi_var : forall x,
      appears_free_in x (tvar x)
  | afi_app1 : forall x t1 t2,
      appears_free_in x t1 -> appears_free_in x (tapp t1 t2)
  | afi_app2 : forall x t1 t2,
      appears_free_in x t2 -> appears_free_in x (tapp t1 t2)
  | afi_abs : forall x y T11 t12,
        y <> x  ->
        appears_free_in x t12 ->
        appears_free_in x (tabs y T11 t12)
  (* pairs *)
  | afi_pair1 : forall x t1 t2,
      appears_free_in x t1 ->
      appears_free_in x (tpair t1 t2)
  | afi_pair2 : forall x t1 t2,
      appears_free_in x t2 ->
      appears_free_in x (tpair t1 t2)
  | afi_fst : forall x t,
      appears_free_in x t ->
      appears_free_in x (tfst t)
  | afi_snd : forall x t,
      appears_free_in x t ->
      appears_free_in x (tsnd t)
  (* booleans *)
  | afi_if0 : forall x t0 t1 t2,
      appears_free_in x t0 ->
      appears_free_in x (tif t0 t1 t2)
  | afi_if1 : forall x t0 t1 t2,
      appears_free_in x t1 ->
      appears_free_in x (tif t0 t1 t2)
  | afi_if2 : forall x t0 t1 t2,
      appears_free_in x t2 ->
      appears_free_in x (tif t0 t1 t2)
.

Hint Constructors appears_free_in.

Definition closed (t:tm) :=
  forall x, ~ appears_free_in x t.

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

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

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

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

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

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

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

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

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

Lemma step_deterministic :
   deterministic step.
Proof with eauto.
   unfold deterministic.
   (* FILL IN HERE *) Admitted.

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

(** Now for the actual normalization proof.

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

    Here's the key definition: *)

Definition halts  (t:tm) : Prop :=  exists t', t ==>* t' /\  value t'.

(** A trivial fact: *)

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

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

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

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

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

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

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

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

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

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

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

Fixpoint R (T:ty) (t:tm) {struct T} : Prop :=
  has_type empty t T /\ halts t /\
  (match T with
   | TBool  => True
   | TArrow T1 T2 => (forall s, R T1 s -> R T2 (tapp t s))
(* FILL IN HERE *)
   | TProd T1 T2 => False (* ... and delete this line *)
   end).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Lemma step_preserves_R' : forall T t t',
  has_type empty t T -> (t ==> t') -> R T t' -> R T t.
Proof.
  (* FILL IN HERE *) Admitted.

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

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

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

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

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

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

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

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

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

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

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

Definition env := list (id * tm).

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

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

Definition tass := list (id * ty).

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

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

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

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

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

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

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

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

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

Lemma vacuous_substitution : forall  t x,
     ~ appears_free_in x t  ->
     forall t', [x:=t']t = t.
Proof with eauto.
  (* FILL IN HERE *) Admitted.

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

Lemma subst_not_afi : forall t x v, closed v ->  ~ appears_free_in x ([x:=v]t).
Proof with eauto.  (* rather slow this way *)
  unfold closed, not.
  t_cases (induction t) Case; intros x v P A; simpl in A.
    Case "tvar".
     destruct (eq_id_dec x i)...
       inversion A; subst. auto.
    Case "tapp".
     inversion A; subst...
    Case "tabs".
     destruct (eq_id_dec x i)...
       inversion A; subst...
       inversion A; subst...
    Case "tpair".
     inversion A; subst...
    Case "tfst".
     inversion A; subst...
    Case "tsnd".
     inversion A; subst...
    Case "ttrue".
     inversion A.
    Case "tfalse".
     inversion A.
    Case "tif".
     inversion A; subst...
Qed.

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

Lemma swap_subst : forall t x x1 v v1, x <> x1 -> closed v -> closed v1 ->
                   [x1:=v1]([x:=v]t) = [x:=v]([x1:=v1]t).
Proof with eauto.
 t_cases (induction t) Case; intros; simpl.
  Case "tvar".
   destruct (eq_id_dec x i); destruct (eq_id_dec x1 i).
      subst. apply ex_falso_quodlibet...
      subst. simpl. rewrite eq_id. apply subst_closed...
      subst. simpl. rewrite eq_id. rewrite subst_closed...
      simpl. rewrite neq_id... rewrite neq_id...
  (* FILL IN HERE *) Admitted.

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

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

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

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

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

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

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

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

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

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

(* FILL IN HERE *)

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

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

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

Lemma mextend_drop : forall (c: tass) Gamma x x',
       mextend Gamma (drop x c) x' = if eq_id_dec x x' then Gamma x' else mextend Gamma c x'.
   induction c; intros.
      destruct (eq_id_dec x x'); auto.
      destruct a. simpl.
      destruct (eq_id_dec i x).
         subst. rewrite IHc.
            destruct (eq_id_dec x x').  auto. unfold extend. rewrite neq_id; auto.
         simpl. unfold extend.  destruct (eq_id_dec i x').
            subst.
               destruct (eq_id_dec x x').
                  subst. exfalso. auto.
                  auto.
           auto.
Qed.

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

(** These are strightforward. *)

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

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

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

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

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

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

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

(* FILL IN HERE *)

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

(** We finally put everything together.

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

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

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

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

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

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

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

  (* FILL IN HERE *) Admitted.

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

Theorem normalization : forall t T, has_type empty t T -> halts t.
Proof.
  intros.
  replace t with (msubst nil t) by reflexivity.
  apply (@R_halts T).
  apply (msubst_R nil); eauto.
  eapply V_nil.
Qed.

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


(**
CoLoR, a Coq library on rewriting and termination.
See the COPYRIGHTS and LICENSE files.

- Frederic Blanqui, 2009-03-19 (setoid)
- Adam Koprowski and Johannes Waldmann, 2008-01
*)

Set Implicit Arguments.

From CoLoR Require Import AArcticBasedInt Matrix OrdSemiRing VecUtil AMonAlg SN
     RelUtil NatUtil AWFMInterpretation LogicUtil AMatrixBasedInt BoolUtil
     ListUtil.
Import ArcticMatrix.

Definition matrixInt := @matrixInt A matrix.
Definition mkMatrixInt := @mkMatrixInt A matrix.

(***********************************************************************)
(** Condition for an arctic interpretation to be valid *)

Section Somewhere_finite.

  Variable dim : nat.
  Variable dim_pos : dim > 0.

  Definition somewhere_finite n (fi : matrixInt dim n) :=
    Vexists (fun m => get_elem m dim_pos dim_pos <> MinusInf) (args fi)
    \/ Vnth (const fi) dim_pos <> MinusInf.

  Definition bsomewhere_finite n (fi : matrixInt dim n) :=
    bVexists (fun m => is_finite (get_elem m dim_pos dim_pos)) (args fi)
    || is_finite (Vnth (const fi) dim_pos).

  Lemma bsomewhere_finite_ok : forall n (fi : matrixInt dim n),
    bsomewhere_finite fi = true <-> somewhere_finite fi.

  Proof.
    intros. unfold bsomewhere_finite, somewhere_finite.
    rewrite orb_eq, is_finite_ok, bVexists_ok. refl. intro. apply is_finite_ok.
  Qed.

  Variable sig : Signature.
  Variable trsInt : forall f : sig, matrixInt dim (arity f).

  Variable Fs : list sig.
  Variable Fs_ok : forall f : sig, In f Fs.

  Lemma fin_somewhere_finite :
    forallb (fun f => bsomewhere_finite (trsInt f)) Fs = true ->
    forall f : sig, somewhere_finite (trsInt f).

  Proof.
    rewrite forallb_forall. intros H f. rewrite <- bsomewhere_finite_ok.
    apply H. apply Fs_ok.
  Qed.

End Somewhere_finite.

Arguments fin_somewhere_finite [dim] _ [sig] _ [Fs] _ _ _.

Ltac somewhere_finite Fs_ok :=
  apply (fin_somewhere_finite _ _ Fs_ok);
    (check_eq || fail 10 "invalid arctic interpretation").

(***********************************************************************)
(** Module type for proving termination with an arctic interpretation *)

Module Type TArcticInt.

  Parameter sig : Signature.
  Parameter dim : nat.
  Parameter dim_pos : dim > 0.
  Parameter trsInt : forall f : sig, matrixInt dim (arity f).
  Parameter trsIntOk : forall f : sig, somewhere_finite dim_pos (trsInt f).

End TArcticInt.

Module ArcticInt (Import AI : TArcticInt).

  Module AB <: TArcticBasedInt.

    Module OSR := ArcticOrdSemiRingT.
    Module M := ArcticMatrix.
    Definition sig := sig.
    Definition dim := dim.
    Definition dim_pos := dim_pos.
    Definition trsInt := trsInt.

  End AB.

  Module Export AIBase := ArcticBasedInt AB.

  Module Export MonotoneAlgebra <: MonotoneAlgebraType.

    Definition Sig := Sig.

    Lemma mat_times_vec_at0_positive n (m : matrix n n)
      (v : vector A n) (dim_pos : n > 0) :
      get_elem m dim_pos dim_pos <> MinusInf ->
      Vnth v dim_pos <> MinusInf ->
      Vnth (mat_vec_prod m v) dim_pos <> MinusInf.

    Proof.
      destruct n; intros. lia.
      VSntac v. unfold matrix in m. VSntac m.
      unfold mat_vec_prod, col_mat_to_vec, get_col. rewrite Vnth_map.
      set (w := mat_mult_spec). unfold get_elem, get_row in w. rewrite w.
      simpl. VSntac (Vhead m). unfold dot_product.
      simpl. rewrite Aplus_comm. apply arctic_plus_notInf_left.
      apply arctic_mult_notInf.
      rewrite H2 in H. unfold get_elem in H. simpl in H.
      rewrite Vhead_nth, <- (Vnth_eq (Vhead m) dim_pos (lt_O_Sn n)); trivial.
      rewrite H1 in H0. hyp.
    Qed.

    Notation mat_times_vec := (@mat_vec_prod dim dim).
    Notation mint := (matrixInt dim).

    Notation "x >_0 y" := (gtx x y) (at level 70).

    Lemma gtx_plus_compat : forall m m' n n',
      m >_0 m' -> n >_0 n' -> m + n >_0 m' + n'.

    Proof.
      intros. destruct H. destruct H0.
      left. apply plus_gt_compat; hyp.
      destruct H0. rewrite H0, H1, !Aplus_0_r. left. hyp.
      destruct H. rewrite H, H1, !Aplus_0_l. hyp.
    Qed.

    Lemma gtx_mult_compat : forall m m' n n',
      m >_0 m' -> n >>= n' -> m * n >_0 m' * n'.

    Proof.
      intros.
      destruct m; destruct m'; destruct n; destruct n';
        destruct H; destruct H0; simpl;
        try solve
          [ exfalso; auto
          | intuition; discr
          | left; simpl; auto
          | left; simpl in *; lia
          | right; auto
          ].
      left. simpl. injection H0. intro. subst n. simpl in H. lia.
    Qed.

    Lemma eval_some_notInf : forall n (mi : mint n) (v : vector dom n),
      Vexists (fun m => get_elem m dim_pos dim_pos <> MinusInf) (args mi) ->
      Vfold_left_rev Aplus A0
      (Vmap (fun v => Vnth v dim_pos)
        (Vmap2 mat_times_vec (args mi) (Vmap dom2vec v))) <> MinusInf.

    Proof.
      induction n; intros; simpl; destruct mi.
      VOtac. auto.
      simpl in H. VSntac args. rewrite H0 in H; simpl. destruct H.
      rewrite Aplus_comm. apply arctic_plus_notInf_left.
      apply mat_times_vec_at0_positive. hyp.
      VSntac v. simpl. destruct (Vhead v).
      unfold vec_invariant, Conf.vec_at0 in v0. simpl in *.
      apply ge_A1_not_minusInf. hyp.
      apply arctic_plus_notInf_left.
      rewrite <- Vmap_tail.
      apply (IHn (mkMatrixInt const (Vtail args))). hyp.
    Qed.

    Lemma mi_eval_at0 : forall n (mi : matrixInt dim n) (v : vector dom n),
      somewhere_finite dim_pos mi ->
      vec_at0 (mi_eval_aux mi (Vmap dom2vec v)) <> MinusInf.

    Proof.
      intros. unfold mi_eval_aux, vec_at0.
      rewrite vector_plus_nth. destruct H.
      rewrite add_vectors_nth. apply arctic_plus_notInf_left.
      apply eval_some_notInf. hyp.
      rewrite Aplus_comm. apply arctic_plus_notInf_left. hyp.
    Qed.

    Lemma mi_eval_ok : forall f v,
      vec_invariant (mi_eval_aux (trsInt f) (Vmap dom2vec v)).

    Proof.
      intros. unfold vec_invariant, Conf.vec_at0.
      apply not_minusInf_ge_A1.
      set (w := mi_eval_at0). unfold vec_at0 in w. apply w.
      apply trsIntOk.
    Qed.

    Definition I := I mi_eval_ok.

    Definition succ := AIBase.succ.
    Definition succ' := AIBase.succ'.
    Definition succ'_sub := @AIBase.succ'_sub gtx_plus_compat gtx_mult_compat
      mi_eval_ok.
    Definition succ'_dec := AIBase.succ'_dec.

    Definition succeq := MBI.succeq.
    Definition succeq' := MBI.succeq'.
    Definition succeq'_sub := @MBI.succeq'_sub mi_eval_ok.
    Definition succeq'_dec := MBI.succeq'_dec.

    Definition refl_succeq := MBI.refl_succeq.
    Definition monotone_succeq := @MBI.monotone_succeq mi_eval_ok.
    Definition trans_succeq := MBI.trans_succeq.
    Definition trans_succ := AIBase.trans_succ.

    Definition succ_succeq_compat := AIBase.succ_succeq_compat ge_gt_eq.

    Lemma succ_wf : WF succ.

    Proof.
      apply WF_incl with
        (fun x y => vec_at0 (dom2vec x) >> vec_at0 (dom2vec y)).
      intros x y xy.
      destruct
        (@Vforall2_elim_nth _ _ gtx _ (dom2vec x) (dom2vec y) _ dim_pos xy).
      hyp.
      destruct H. destruct x.
      absurd (Vnth x dim_pos = A0).
      apply ge_A1_not_minusInf. hyp. hyp.
      fold (@Rof dom A gt (fun v => vec_at0 (dom2vec v))).
      apply WF_inverse. apply gt_WF.
    Qed.

  End MonotoneAlgebra.

  Ltac prove_cc_succ Fs_ok :=
    fail 10 "arctic matrices cannot be used for proving total termination".

End ArcticInt.


From Test Require Import tactic.

Section FOFProblem.

Variable Universe : Set.
Variable UniverseElement : Universe.

Variable p_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.
Variable goal_ : Prop.
Variable dom_ : Universe -> Prop.

Variable a9_ : Universe.
Variable a8_ : Universe.
Variable a7_ : Universe.
Variable a6_ : Universe.
Variable a5_ : Universe.
Variable a4_ : Universe.
Variable a3_ : Universe.
Variable a2_ : Universe.
Variable a11_ : Universe.
Variable a10_ : Universe.
Variable a1_ : Universe.

Variable ax1_1 : (dom_ a1_ /\ (dom_ a2_ /\ (dom_ a3_ /\ (dom_ a4_ /\ (dom_ a5_ /\ (dom_ a6_ /\ (dom_ a7_ /\ (dom_ a8_ /\ (dom_ a9_ /\ (dom_ a10_ /\ dom_ a11_)))))))))).
Variable ax2_2 : (forall A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 : Universe, ((dom_ A1 /\ (dom_ A2 /\ (dom_ A3 /\ (dom_ A4 /\ (dom_ A5 /\ (dom_ A6 /\ (dom_ A7 /\ (dom_ A8 /\ (dom_ A9 /\ (dom_ A10 /\ dom_ A11)))))))))) -> p_ A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11)).
Variable ax3_3 : (p_ a11_ a10_ a9_ a8_ a7_ a6_ a5_ a4_ a3_ a2_ a1_ -> goal_).

Theorem lemma11_4 : goal_.
Proof.
  time tac.
Qed.

End FOFProblem.


Set Implicit Arguments.
Unset Strict Implicit.

Require Import HoTT.Homotopy.
Require Import pointed_spaces.
Require Import tactics.
Require Import some_lemmas.

Import pt_map_notation.

Section smash_product.

Variables A B : pt_type.

Reserved Notation "< A , B >"
 (at level 40, B at next level, left associativity).

Record smash_data : Type := {
  smash_carrier :> Type ;
  smash_pair : forall (a : A) (b : B), smash_carrier
    where "< a , b >" := (smash_pair a b)
;
  base_1 : smash_carrier ;
  base_2 : smash_carrier ;
  contract_1 : forall (a : A), <a, point B> = base_1 ;
  contract_2 : forall (b : B), <point A, b> = base_2 ;

  smash_elim : forall (P : smash_carrier -> Type)
     (d_pair : forall a b, P (< a , b>) )
     (d_base_1 : P base_1)
     (d_base_2 : P base_2)
     (d_contract_1 : forall a : A,
        transport (contract_1 a) (d_pair a (point B)) =
             d_base_1)
     (d_contract_2 : forall b : B,
        transport (contract_2 b) (d_pair (point A) b) =
             d_base_2)

      , forall x : smash_carrier, P x
;
  smash_comp_pair : forall (P : smash_carrier -> Type)
     (d_pair : forall a b, P (< a , b>) )
     (d_base_1 : P base_1)
     (d_base_2 : P base_2)
     (d_contract_1 : forall a : A,
        transport (contract_1 a) (d_pair a (point B)) =
             d_base_1)
     (d_contract_2 : forall b : B,
        transport (contract_2 b) (d_pair (point A) b) =
             d_base_2),
       forall a b,
       smash_elim  (*d_pair*) (*d_base_1*) (*d_base_2*)
          d_contract_1 d_contract_2
            (<a, b>) = d_pair a b
;

  smash_comp_base_1 : forall (P : smash_carrier -> Type)
     (d_pair : forall a b, P (< a , b>) )
     (d_base_1 : P base_1)
     (d_base_2 : P base_2)
     (d_contract_1 : forall a : A,
        transport (contract_1 a) (d_pair a (point B)) =
             d_base_1)
     (d_contract_2 : forall b : B,
        transport (contract_2 b) (d_pair (point A) b) =
             d_base_2),

       smash_elim  (*d_pair*) (*d_base_1*) (*d_base_2*)
          d_contract_1 d_contract_2
            base_1 = d_base_1
;
 smash_comp_base_2 : forall (P : smash_carrier -> Type)
     (d_pair : forall a b, P (< a , b>) )
     (d_base_1 : P base_1)
     (d_base_2 : P base_2)
     (d_contract_1 : forall a : A,
        transport (contract_1 a) (d_pair a (point B)) =
             d_base_1)
     (d_contract_2 : forall b : B,
        transport (contract_2 b) (d_pair (point A) b) =
             d_base_2),

       smash_elim  (*d_pair*) (*d_base_1*) (*d_base_2*)
          d_contract_1 d_contract_2
            base_2 = d_base_2

;

  smash_comp_contract_1 : forall (P : smash_carrier -> Type)
     (d_pair : forall a b, P (< a , b>) )
     (d_base_1 : P base_1)
     (d_base_2 : P base_2)
     (d_contract_1 : forall a : A,
        transport (contract_1 a) (d_pair a (point B)) =
             d_base_1)
     (d_contract_2 : forall b : B,
        transport (contract_2 b) (d_pair (point A) b) =
             d_base_2),
    forall a : A,
      map_dep (smash_elim d_contract_1 d_contract_2) (contract_1 a) =
          (map (transport (contract_1 a)) ((smash_comp_pair
d_contract_1 d_contract_2) a (point B)))
              @ (d_contract_1 a) @
                ! (smash_comp_base_1
d_contract_1 d_contract_2)

(* thanks PLL *)

}.

Definition smash_elim_simp (X : smash_data)
      (Y : pt_type)
     (f : forall (a : A) (b : B), Y)
     (Ya Yb : Y)
     (Ha : forall a : A, f a (point B) = Ya)
     (Hb : forall b : B, f (point A) b = Yb) : X -> Y.
Proof.
  apply
   (smash_elim (P := (fun _ => Y))
                    (d_pair := f)
                    (d_base_1 := Ya)
                    (d_base_2 := Yb)
                      ).
  intro a.
  pathvia (transport (P:=fun _ : X => Y)(contract_1 X a) Ya).
  apply (map _ (Ha a)).
  apply trans_trivial.
  intro b.
  pathvia (transport (P:=fun _ : X => Y)(contract_2 X b) Yb).
  apply (map _ (Hb b)).
  apply trans_trivial.
Defined.

Section smash_elim_simp_rules.

Variable X : smash_data.

Variables     (Y : pt_type)
     (f : forall (a : A) (b : B), Y)
     (Ya Yb : Y)
     (Ha : forall a : A, f a (point B) = Ya)
     (Hb : forall b : B, f (point A) b = Yb).

Lemma smash_elim_simp_pair : forall a b,
  @smash_elim_simp X _ f _ _ Ha Hb (smash_pair X a b) = f a b.
Proof.
  intros a b.
  apply  (@smash_comp_pair X (fun _ => Y) f Ya Yb).
Defined.

Lemma smash_elim_simp_base_1 :
  @smash_elim_simp X _ f _ _ Ha Hb (base_1 X) = Ya.
Proof.
  apply (@smash_comp_base_1 X (fun _ => Y) f Ya Yb).
Defined.

Lemma smash_elim_simp_base_2 :
  @smash_elim_simp X _ f _ _ Ha Hb (base_2 X) = Yb.
Proof.
  apply (@smash_comp_base_2 X (fun _ => Y) f Ya Yb).
Defined.

(*
Lemma smash_elim_simp_contract_1 :
   forall a : A,
  map (@smash_elim_simp X _ f _ _ Ha Hb) (contract_1 a) =
*)

End smash_elim_simp_rules.

Definition smash (X : smash_data) : pt_type := {|
   carrier := (* smash_carrier *) X ;
   point := smash_pair X (point A) (point B)
|}.

(** a path from (a, b0) to (a0,b0)  *)

Definition edge_connected_1 (X : smash_data) (a : A) :
  smash_pair _ a (point B) = smash_pair X (point A)(point B).
pathvia (base_1 X).
(*apply (concat (y:=base_1 X)).*)
apply (contract_1 X a).
apply (! contract_1 X _).
Defined.

Lemma edge_connected_1_refl (X : smash_data) :
   edge_connected_1 X (point A) = idpath.
Proof.
(*  unfold edge_connected_1. *)
  apply opposite_right_inverse.
Qed.

Definition edge_connected_2 (X : smash_data) (b : B) :
  smash_pair _ (point A) b = smash_pair X (point A)(point B).
pathvia (base_2 X).
apply (contract_2 X _ ).
apply (! contract_2 _ _ ).
Defined.

Lemma edge_connected_2_refl (X : smash_data) :
   edge_connected_2 X (point B) = idpath.
Proof.
(*  unfold edge_connected_2. *)
  apply opposite_right_inverse.
Qed.

End smash_product.

Module Import smash_notation.

Notation "< a , b >" := (smash_pair _ a b)
 (at level 40, B at next level, left associativity).

End smash_notation.

Section smash_product_functorial.

Variables A B C D : pt_type.

Variable f : A .-> C.
Variable g : B .-> D.

Variable AB : smash_data A B.
Variable CD : smash_data C D.

Definition smashf_carrier : smash AB -> smash CD.
apply (@smash_elim_simp _ _ AB (smash CD)
        (fun a b => smash_pair _ (pr1 f a) (pr1 g b) )
        (base_1 CD)
        (base_2 CD)
).
- intro a.
(*  rewrite (pr2 g). *)
  pathvia (smash_pair CD (pr1 f a)(point D)).
  apply (map _ (pr2 g)).
  apply (contract_1).
- intro b.
  pathvia (smash_pair CD (point C)(pr1 g b)).
  + apply map_twovar_2eq_nondep.
    apply (pr2 f).
  + apply contract_2.
Defined.

Definition smashf : smash AB .-> smash CD.
exists smashf_carrier.
unfold smashf_carrier.
change (point (smash AB)) with
     (smash_pair AB (point A) (point B)).
(*rewrite smash_elim_simp_pair.*)
pathvia (smash_pair CD (pr1 f (point A))(pr1 g (point B))).
About smash_elim_simp_pair.
- simpl. apply ( smash_elim_simp_pair AB (Y:=smash CD)
      (f:=fun a b => smash_pair CD (pr1 f a) (pr1 g b))).
- change (point (smash CD)) with
     (smash_pair CD (point C) (point D)).
  Check @map_twovar.
  pathvia (smash_pair CD (pr1 f (point A)) (point D)).
  + apply (map _ (pr2 g)).
  + apply map_twovar_2eq_nondep.
    apply (pr2 f).
Defined.

(* need functorial properties *)

End smash_product_functorial.


Require Import Coq.ZArith.BinInt.
Require Import Crypto.Arithmetic.Saturated.UniformWeight.
Require Import Crypto.Util.Tuple.
Require Import Crypto.Util.Decidable.
Require Import Crypto.Util.Tactics.DestructHead.

Fixpoint small_Decidable' {bound n} : forall (p : Tuple.tuple' Z n), Decidable (small (n:=S n) bound p).
Proof.
  refine match n as n return forall p : Tuple.tuple' Z n, id (Decidable (small (n:=S n) bound p)) with
         | 0
           => fun p : Z
              => if dec (0 <= p < bound)%Z then left _ else right _
         | S n'
           => fun p : Tuple.tuple' Z n' * Z
              => if dec (0 <= snd p < bound)%Z
                 then if dec (small (n:=S n') bound (fst p))%Z
                      then left _
                      else right _
                 else right _
         end;
    unfold id, small in *; simpl in *;
      [ clear small_Decidable' n
      | clear small_Decidable' n
      | clear small_Decidable'; simpl in *.. ];
      [ abstract (simpl in *; intros; destruct_head'_or; subst; auto; exfalso; assumption)
      | abstract (simpl in *; intros; destruct_head'_or; subst; auto; exfalso; assumption)
      | abstract (destruct p; simpl in *; intros; destruct_head'_or; subst; auto).. ].
Defined.

Global Instance small_Decidable {bound n} : forall (p : Tuple.tuple Z n), Decidable (small bound p).
Proof.
  destruct n; simpl; [ left | apply small_Decidable' ].
  intros ??; exfalso; assumption.
Defined.


(*
Copyright © 2006-2008 Russell O’Connor
Copyright © 2020 Vincent Semeria

Permission is hereby granted, free of charge, to any person obtaining a copy of
this proof and associated documentation files (the "Proof"), to deal in
the Proof without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Proof, and to permit persons to whom the Proof is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Proof.

THE PROOF IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.
*)

Require Import CoRN.algebra.RSetoid.
Require Import CoRN.model.totalorder.QposMinMax.
Require Import CoRN.model.metric2.Qmetric.
Require Import CoRN.metric2.Limit.
Require Import Coq.QArith.Qabs.
Require Import Coq.Arith.Arith.
Require Import Coq.QArith.Qpower.
Require Import CoRN.reals.fast.LazyNat.
Require Import Coq.setoid_ring.Ring MathClasses.interfaces.abstract_algebra MathClasses.theory.streams.
Require Export MathClasses.theory.series.
Require Import MathClasses.interfaces.abstract_algebra MathClasses.theory.streams.

Opaque Qabs.
Local Open Scope Q_scope.

(**
** Specific results for streams on [Q]
*)

(** [everyOther] preserves limits. *)
Lemma everyOther_nbz : forall (s : Stream Q) (e : QposInf),
    (NearBy 0 e s) -> NearBy 0 e (everyOther s).
Proof.
 cofix everyOther_nbz.
 intros [s [b r]] x [H [_ Hs]].
 constructor;[|apply everyOther_nbz];assumption.
Qed.

#[global]
Instance everyOther_zl `{Hx : !Limit s 0} : Limit (everyOther s) 0.
Proof.
 intros e.
 assert (H:=Hx e). clear Hx.
 revert s H.
 fix everyOther_zl 2.
 intros x [H|H].
  left.
  apply everyOther_nbz.
  assumption.
 case (H tt);[intros X |intros X].
  right; left.
  clear - x X.
  abstract ( destruct x as [a [b x]]; destruct X; apply everyOther_nbz; assumption).
 right; intros _.
 apply everyOther_zl.
 apply X.
 constructor.
Defined.

(** [mult_Streams] preserves convergeing to 0. *)
Lemma mult_Streams_nbz : forall {s1 s2 : Stream Q} {x : QposInf},
    (NearBy 0 x s1)
    -> forall {y : QposInf}, NearBy 0 y s2
             -> NearBy 0 (x*y) (mult_Streams s1 s2).
Proof.
 unfold NearBy.
 cofix mult_Streams_nbz.
 intros s1 s2 x [Ha0 Hs1] y [Hb0 Hs2].
 constructor.
 2: apply (mult_Streams_nbz (CoqStreams.tl s1) (CoqStreams.tl s2)); assumption.
 destruct x as [x|];[|constructor].
 destruct y as [y|];[|constructor].
 simpl.
 unfold Qball.
 unfold QAbsSmall.
 setoid_replace ((CoqStreams.hd s1 * CoqStreams.hd s2)%mc - 0)%Q
   with ((CoqStreams.hd s1 - 0) * (CoqStreams.hd s2 - 0)).
 apply Qmult_AbsSmall; assumption.
 ring_simplify. reflexivity.
Qed.

(* The multiplication of a bounded stream b by a stream a
   converging to 0 converges to 0. *)
Lemma mult_Streams_zl : forall (a b : Stream Q),
    (Limit a 0) -> forall (x:Qpos), NearBy 0 x b ->
                              Limit (mult_Streams a b) 0.
Proof.
 intros a b Ha x Hb e.
 assert (H:=Ha (e * (Qpos_inv x))%QposInf).
 generalize b Hb.
 clear b Hb.
 induction H; intros b Hb.
  left.
  abstract ( destruct e as [e|];[|apply ForAll_True];
             assert (Heq:proj1_sig e== proj1_sig ((e*Qpos_inv x)*x)%Qpos);[
    simpl; field; apply Qpos_nonzero
             |rewrite -> (NearBy_comp _ _ (ball_refl _ 0 (Qle_refl 0)) _ _ Heq );
              apply (mult_Streams_nbz H Hb)] ).
 right.
 simpl.
 rename H0 into IHExists.
 intros.
 apply (IHExists tt).
  apply Limit_tl; assumption.
 destruct Hb; assumption.
Defined.

(**
*** [StreamBounds]
[StreamBounds] says that one stream pointwise bounds the absolute value
of the other. *)
Definition StreamBounds (a b : Stream Q)
  := ForAll (fun (x:Stream (Q*Q)) => let (a,b):=(CoqStreams.hd x) in QAbsSmall a b)
            (zipWith pair a b).

(** If the bounding stream goes to 0, so does the bounded stream. *)
Lemma Stream_Bound_nbz : forall a b e, (StreamBounds a b) -> NearBy 0 e a -> NearBy 0 e b.
Proof.
 cofix Stream_Bound_nbz.
 intros a b e Hb Ha.
 constructor.
  destruct Hb as [[Hb1 Hb2] _].
  destruct e as [e|];[|constructor].
  destruct Ha as [[Ha1 Ha2] _].
  simpl in *.
  split.
   apply Qle_trans with (-(CoqStreams.hd a -0)).
    apply Qopp_le_compat.
    assumption.
   ring_simplify.
   assumption.
  apply Qle_trans with (CoqStreams.hd a - 0).
   ring_simplify.
   assumption.
  assumption.
 eapply Stream_Bound_nbz.
  destruct Hb as [_ Hb].
  change (StreamBounds (CoqStreams.tl a) (CoqStreams.tl b)) in Hb.
  apply Hb.
 destruct Ha as [_ Ha].
 assumption.
Qed.

Lemma Stream_Bound_zl : forall a b, (StreamBounds a b) -> Limit a 0 -> Limit b 0.
Proof.
 intros a b H Ha e.
 assert (Ha':=(Ha e)); clear Ha.
 generalize b H; clear b H.
 induction Ha'; intros b Hb.
  left.
  apply Stream_Bound_nbz with x; assumption.
 right.
 rename H0 into IHHa'.
 intros _.
 apply (IHHa' tt).
 destruct Hb; assumption.
Defined.

Section Qpowers.
Variable a : Q.

Hypothesis Ha : 0 <= a <= 1.

(** It is decreasing and nonnegative when a is between 0 and 1. *)
Lemma powers_help_dnn : forall x, (0 <= x) -> DecreasingNonNegative (powers_help a x).
Proof.
 intros x Hx.
 destruct Ha as [Ha0 Ha1].
 generalize x Hx; clear x Hx.
 cofix powers_help_dnn.
 intros b Hb.
 constructor.
  simpl.
  split.
  rewrite <- (Qmult_0_l a). apply Qmult_le_compat_r; assumption.
  rewrite Qmult_comm.
  rewrite <- (Qmult_1_l b) at 2.
  apply Qmult_le_compat_r. exact Ha1. exact Hb.
 apply powers_help_dnn.
 rewrite <- (Qmult_0_l a). apply Qmult_le_compat_r; assumption.
Qed.

Lemma powers_dnn : DecreasingNonNegative (powers a).
Proof.
 apply powers_help_dnn.
 discriminate.
Qed.

Lemma powers_help_nbz : forall x,
    0 <= x <= 1 -> NearBy 0 (Qpos2QposInf (1#1)) (powers_help a x).
Proof.
 cofix powers_help_nbz.
 intros b [Hb0 Hb1].
 destruct Ha as [Ha0 Ha1].
 constructor.
  simpl.
  unfold Qball.
  unfold QAbsSmall. setoid_replace (b-0)%Q with b.
  2: unfold Qminus; apply Qplus_0_r.
  split;simpl.
   apply Qle_trans with 0;[discriminate|assumption].
  assumption.
 simpl.
 apply powers_help_nbz.
 split.
 rewrite <- (Qmult_0_l a). apply Qmult_le_compat_r; assumption.
 apply (Qle_trans _ (1*a)).
 apply Qmult_le_compat_r; assumption.
 rewrite Qmult_1_l. exact Ha1.
Qed.

Lemma powers_nbz : NearBy 0 (Qpos2QposInf (1#1)) (powers a).
Proof.
 apply powers_help_nbz.
 split; discriminate.
Qed.
End Qpowers.

(**
*** [ppositives]
The stream of postive numbers (as positive).

We do not use [positives] because [positive] does not form a semiring.
*)
CoFixpoint ppositives_help (n:positive) : Stream positive :=
Cons n (ppositives_help (Pos.succ n)).

Definition ppositives := ppositives_help 1.

Lemma Str_nth_ppositives : forall n, Str_nth n ppositives ≡ P_of_succ_nat n.
Proof.
 intros n.
 unfold ppositives.
 apply nat_of_P_inj.
 rewrite nat_of_P_o_P_of_succ_nat_eq_succ.
 change (S n) with ((nat_of_P 1) + n)%nat.
 generalize 1%positive.
 induction n.
  intros c.
  rewrite plus_comm.
  reflexivity.
 intros c.
 unfold Str_nth in *.
 simpl.
 rewrite IHn.
 rewrite nat_of_P_succ_morphism.
 apply plus_n_Sm.
Qed.

Lemma Str_nth_ppositives' n
  : inject_Z (Zpos (Str_nth n ppositives)) = Str_nth n positives.
Proof.
  rewrite Str_nth_ppositives, Str_nth_positives.
  rewrite Z.P_of_succ_nat_Zplus.
  rewrite <-(naturals.to_semiring_unique (Basics.compose inject_Z Z_of_nat)).
  unfold Basics.compose.
  rewrite <-(rings.preserves_1 (f:=inject_Z)).
  rewrite <-rings.preserves_plus.
  now rewrite commutativity.
Qed.

(**
*** [Qrecip_positives]
The stream of 1/n.
*)
Definition Qrecip_positives := CoqStreams.map (fun x => 1#x) ppositives.

Lemma Str_nth_Qrecip_positives : forall n, Str_nth n Qrecip_positives = 1#(P_of_succ_nat n).
Proof.
 intros n.
 unfold Qrecip_positives.
 rewrite Str_nth_map.
 rewrite Str_nth_ppositives.
 reflexivity.
Qed.

Lemma Str_nth_Qrecip_positives' n : Str_nth n Qrecip_positives = / Str_nth n positives.
Proof.
  unfold Qrecip_positives.
  rewrite Str_nth_map.
  rewrite Qmake_Qdiv.
  rewrite Str_nth_ppositives'.
  apply (left_identity (/ Str_nth n positives)).
Qed.

(** The limit of [recip_positives] is 0. *)
Lemma Qrecip_positives_help_nbz : forall (x: Qpos) (q:positive),
    (Zpos (Qden (proj1_sig x)) <= Zpos q)%Z
    -> NearBy 0 (Qpos2QposInf x) (CoqStreams.map (fun x => 1#x) (ppositives_help q)).
Proof.
  assert (∀ (q n d : positive),
    (Zpos d <= Zpos q)%Z
    → NearBy 0 (Qpos2QposInf (n # d)) (CoqStreams.map (λ x : positive, 1 # x) (ppositives_help q))).
 { cofix Qrecip_positives_help_nbz.
 intros q n d Hpq.
 constructor.
 - simpl.
   unfold Qball, QAbsSmall, Qminus.
   rewrite Qplus_0_r.
  split. discriminate.
  change (1*Zpos d <= Zpos n*Zpos q)%Z.
  apply Zmult_le_compat.
  apply Pos.le_1_l. exact Hpq.
  discriminate. discriminate.
 - apply Qrecip_positives_help_nbz.
 clear Qrecip_positives_help_nbz.
 rewrite Zpos_succ_morphism.
 apply (Z.le_trans _ _ _ Hpq).
 apply Z.le_succ_diag_r. }
 intros. destruct x as [[n d] xpos].
 destruct n as [|n|n]. inversion xpos. 2: inversion xpos.
 apply H. exact H0.
Qed.

(* Make a lazy list of LazyFurthers. *)
Fixpoint Qrecip_positives_help_Exists P (n:LazyNat) (p:positive)
  (H : LazyExists P (CoqStreams.map (fun x => (1#x)) (ppositives_help (Pplus_LazyNat p n))))  { struct n }
  : LazyExists P (CoqStreams.map (fun x => (1#x)) (ppositives_help p)).
Proof.
  destruct n.
  - exact H.
  - apply LazyFurther.
    exact (fun _ => Qrecip_positives_help_Exists P (l tt) (Pos.succ p) H).
Defined.

Lemma Qrecip_positives_nbz : forall (n : Z) (d : positive) (U : 0 < n # d),
    NearBy 0 (Qpos2QposInf (exist _ (n # d) U))
           (map (λ x : positive, 1 # x)
                (ppositives_help (Pplus_LazyNat 1 (LazyPred (LazyNat_of_P d))))).
Proof.
  intros.
  apply Qrecip_positives_help_nbz.
  induction d using Pind;[simpl;auto with *|].
  autorewrite with UnLazyNat in *.
  rewrite nat_of_P_succ_morphism; assert (H:=lt_O_nat_of_P d);
     destruct (nat_of_P d);[exfalso;auto with *|]; simpl in *;
       replace (Pplus_LazyNat 2 (LazifyNat n0)) with (Pos.succ (Pplus_LazyNat 1 (LazifyNat n0)));[
         repeat rewrite Zpos_succ_morphism; auto with * |]; clear -n0;
           change 2%positive with (Pos.succ 1); generalize 1%positive;
             induction n0;intros p;[reflexivity|]; simpl in *; rewrite IHn0; reflexivity.
Qed.

#[global]
Instance Qrecip_positives_zl : Limit Qrecip_positives 0.
 intros [[[n d] U] | ]; [| left; apply ForAll_True].
 unfold Qrecip_positives.
 unfold ppositives.
 apply Qrecip_positives_help_Exists with (LazyPred (LazyNat_of_P d)).
 left. apply Qrecip_positives_nbz.
Defined.

(** [recip_positives] is [DecreasingNonNegative]. *)
#[global]
Instance Qrecip_positives_dnn : DecreasingNonNegative Qrecip_positives.
Proof.
 unfold Qrecip_positives.
 unfold ppositives.
 generalize (1%positive) at 2.
 cofix Qrecip_positives_dnn.
 intros p.
 constructor.
  simpl.
  split.
   discriminate.
  change (Zpos p <= Zpos (Pos.succ p))%Z.
  repeat rewrite Zpos_succ_morphism.
  auto with *.
 simpl.
 apply Qrecip_positives_dnn.
Qed.

(**
*** [pfactorials]
The stream of factorials as positives.

Again, we do not use [factorials] because [positive] does not form a semiring.
*)
CoFixpoint pfactorials_help (n c:positive) : Stream positive :=
Cons c (pfactorials_help (Pos.succ n) (n*c)).

Definition pfactorials := pfactorials_help 1 1.

Lemma Str_nth_pfactorials : forall n, nat_of_P (Str_nth n pfactorials) ≡ fact n.
Proof.
 unfold pfactorials.
 intros n.
 pose (ONE:=1%positive).
 replace (fact n) with ((nat_of_P 1)*fact (pred (nat_of_P ONE) + n))%nat by (simpl;auto).
 replace (nat_of_P (Str_nth n (pfactorials_help 1 1)))
   with ((fact (pred (nat_of_P ONE)))*(nat_of_P (Str_nth n (pfactorials_help ONE 1))))%nat by (simpl; auto with * ).
 change (pfactorials_help 1 1) with (pfactorials_help ONE 1).
 generalize ONE.
 generalize 1%positive.
 unfold ONE; clear ONE.
 induction n.
  intros a b.
  unfold Str_nth.
  simpl.
  rewrite plus_comm.
  now rewrite mult_comm.
 intros a b.
 unfold Str_nth in *.
 simpl.
 assert (X:=IHn (b*a)%positive (Pos.succ b)).
 clear IHn.
 rewrite nat_of_P_succ_morphism in X.
 rewrite <- plus_n_Sm.
 assert (forall (n m:nat), eq (Z_of_nat n) (Z_of_nat m) -> eq n m).
 { intros i j H. intuition. }
 apply H. clear H.
 apply Zmult_reg_l with (Z.of_nat (nat_of_P b));
   [rewrite positive_nat_Z; auto with *|].
 do 2 rewrite <- (inj_mult (nat_of_P b)).
 apply inj_eq.
 rewrite (Nat.mul_assoc (nat_of_P b) (nat_of_P a)).
 rewrite <- Pos2Nat.inj_mul.
 rewrite <- pred_Sn in X.
 change (S (pred (nat_of_P b) + n))%nat with (S (pred (nat_of_P b)) + n)%nat.
 assert (Z:S (pred (nat_of_P b)) = nat_of_P b).
 { apply (Nat.lt_succ_pred 0). apply Pos2Nat.is_pos. }
 rewrite Z.
 rewrite <- X.
 replace (fact (nat_of_P b)) with (fact (S (pred (nat_of_P b)))) by congruence.
 change (fact (S (pred (nat_of_P b)))) with ((S (pred (nat_of_P b)))*(fact (pred (nat_of_P b))))%nat.
 rewrite Z.
 ring.
Qed.

Lemma Str_nth_pfactorials' n
  : inject_Z (Zpos (Str_nth n pfactorials)) = Str_nth n factorials.
Proof.
  rewrite Str_nth_factorials.
  rewrite <-Str_nth_pfactorials.
  rewrite <-(naturals.to_semiring_unique (Basics.compose inject_Z Z_of_nat)).
  unfold Basics.compose.
  rewrite positive_nat_Z. reflexivity.
Qed.

(**
*** [Qrecip_factorials]
The stream of 1/n!.
**)
Definition Qrecip_factorials := CoqStreams.map (fun x => 1#x) pfactorials.

Lemma Str_nth_Qrecip_factorials : forall n, (Str_nth n Qrecip_factorials) = 1#(P_of_succ_nat (pred (fact n))).
Proof.
 intros n.
 unfold Qrecip_factorials.
 rewrite Str_nth_map.
 rewrite <- Str_nth_pfactorials.
 unfold equiv, stdlib_rationals.Q_eq, Qeq. simpl.
 apply f_equal.
 transitivity (Pos.of_nat (Pos.to_nat (Str_nth n pfactorials))).
 2: apply Pos2Nat.id.
 destruct (Pos.to_nat (Str_nth n pfactorials)) eqn:des.
 2: apply Pos.of_nat_succ.
 exfalso. pose proof (Pos2Nat.is_pos (Str_nth n pfactorials)).
 rewrite des in H. inversion H.
Qed.

Lemma Str_nth_Qrecip_factorials' n : Str_nth n Qrecip_factorials = / Str_nth n factorials.
Proof.
  unfold Qrecip_factorials.
  rewrite Str_nth_map.
  rewrite Qmake_Qdiv.
  rewrite Str_nth_pfactorials'.
  now apply (left_identity (/ Str_nth n factorials)).
Qed.

(** [Qrecip_factorials] is [DecreasingNonNegative]. *)
#[global]
Instance Qrecip_factorials_dnn : DecreasingNonNegative Qrecip_factorials.
Proof.
 unfold Qrecip_factorials.
 unfold pfactorials.
 generalize (1%positive) at 3. generalize (1%positive) at 2.
 cofix Qrecip_factorials_dnn.
 intros a b.
 constructor.
  simpl.
  split.
   discriminate.
  apply (Z.mul_le_mono_nonneg_r 1 (Zpos a) (Zpos b)).
  discriminate. apply Pos.le_1_l.
 simpl.
 apply Qrecip_factorials_dnn.
Qed.

(** The limit of [Qrecip_factorial] is 0. *)
Lemma Qrecip_factorial_bounded
  : StreamBounds Qrecip_positives (CoqStreams.tl Qrecip_factorials).
Proof.
 unfold Qrecip_positives, Qrecip_factorials, ppositives, pfactorials.
 cut (forall (p q:positive), StreamBounds (CoqStreams.map (fun x : positive => 1 # x) (ppositives_help p))
   (CoqStreams.tl (CoqStreams.map (fun x : positive => 1 # x) (pfactorials_help p q)))).
  intros H.
  apply (H 1%positive 1%positive).
 auto with *.
 cofix Qrecip_factorial_bounded.
 constructor.
  simpl.
  split.
   discriminate.
  change (Zpos p <= Zpos p * Zpos q)%Z.
  rewrite Z.mul_comm.
  apply (Z.mul_le_mono_nonneg_r 1 (Zpos q) (Zpos p)).
  discriminate. apply Pos.le_1_l.
 simpl in *.
 apply Qrecip_factorial_bounded.
Qed.

#[global]
Instance Qrecip_factorials_zl : Limit Qrecip_factorials 0.
Proof.
 intros e.
 right.
 intros _.
 apply (Stream_Bound_zl _ _ Qrecip_factorial_bounded).
 apply Qrecip_positives_zl.
Defined.

Section StreamGenerators.
  (* Strictly speaking those are generators of streams with a state X,
     or stream co-algebras, rather than actual streams. Instead of using
     corecursion to produce actual coinductive streams, we directly call
     the generator functions.

     The type Stream Y is isomorphic the type nat -> Y. We use the former
     to compute series such as exp x = sum_k x^k / k!
     because the (k+1)-th term is quickly computed from the k-th term,
     rather than recomputing the power and the factorial from 0 for each k. *)

  Variable X : Type.
  Variable f : X -> X.

  Fixpoint iterate (p : positive) (x : X) : X :=
    match p with
    | xI q => iterate q (iterate q (f x))
    | xO q => iterate q (iterate q x)
    | xH => f x
    end.

  Lemma iterate_one : forall x:X,
      iterate 1 x ≡ f x.
  Proof.
    reflexivity.
  Qed.

  Lemma iterate_shift : forall (p:positive) (x : X),
      f (iterate p x) ≡ iterate p (f x).
  Proof.
    induction p.
    - intro x. simpl.
      rewrite IHp, IHp. reflexivity.
    - intro x. simpl.
      rewrite IHp, IHp. reflexivity.
    - reflexivity.
  Qed.

  Lemma iterate_succ : forall (p:positive) (x : X),
      iterate (Pos.succ p) x ≡ f (iterate p x).
  Proof.
    induction p.
    - intro x. simpl.
      rewrite IHp. f_equal.
      rewrite IHp. f_equal.
      rewrite iterate_shift. reflexivity.
    - intro x. simpl.
      rewrite iterate_shift, iterate_shift.
      reflexivity.
    - reflexivity.
  Qed.

  Lemma iterate_add : forall (p q:positive) (x : X),
      iterate (p+q)%positive x ≡ iterate p (iterate q x).
  Proof.
    apply (Pos.peano_ind
             (fun p => forall (q : positive) (x : X),
                  iterate (p + q) x ≡ iterate p (iterate q x))).
    - intros. rewrite Pos.add_1_l, iterate_succ. reflexivity.
    - intros. rewrite iterate_succ.
      rewrite <- Pos.add_1_l, <- Pos.add_assoc, Pos.add_1_l.
      rewrite iterate_succ, H. reflexivity.
  Qed.

  Variable stop : X -> bool.

  (* iterate_stop p x = iterate q x, where q = p or q < p and
     q is the lowest index such as stop (iterate q) = true.
     Testing whether the recursive iterate_stop stops regrettably
     adds a logarithmic useless number of stop tests.
     This could be improved by returning a pair X*bool to indicate
     that the iteration stopped. We could also try using a LazyNat fuel. *)
  Fixpoint iterate_stop (p : positive) (x : X) : X :=
    match p with
    | xI q => (* p = 2q+1 *)
      let g := f x in
      if stop g then g else
        let h := iterate_stop q g in
        if stop h then h else iterate_stop q h
    | xO q => let g := iterate_stop q x in
             if stop g then g else iterate_stop q g
    | xH => f x
    end.

  (* The q below is even unique. Because it is either p or
     the first index where iterate stops. *)
  Lemma iterate_stop_correct : forall (p:positive) (x:X),
      exists q:positive,
        iterate_stop p x ≡ iterate q x
        /\ (forall r, Pos.lt r q -> stop (iterate r x) ≡ false)
        /\ (p ≡ q
           \/ (Pos.lt q p /\ stop (iterate q x) ≡ true)).
  Proof.
    induction p.
    - intro x. simpl.
      destruct (stop (f x)) eqn:des1.
      exists xH. split. reflexivity.
      split. intros. exfalso; exact (Pos.nlt_1_r r H).
      right. split. rewrite Pos.xI_succ_xO.
      apply Pos.lt_1_succ.
      exact des1.
      destruct (stop (iterate_stop p (f x))) eqn:des.
      + (* Stopped at p+1 by the stop predicate,
           prove that value is the same at 2p+1. *)
        specialize (IHp (f x)) as [q [itereq [H H0]]].
        exists (Pos.succ q). split.
        rewrite itereq, iterate_succ, iterate_shift.
        reflexivity. split.
        apply (Pos.peano_case
                 (fun r => (r < Pos.succ q)%positive → stop (iterate r x) ≡ false)).
        intros. exact des1. intros.
        rewrite iterate_succ, iterate_shift. apply H.
        apply Pos.succ_lt_mono in H1.
        exact H1. right.
        split. rewrite Pos.xI_succ_xO.
        rewrite <- Pos.succ_lt_mono.
        destruct H0. rewrite H0.
        rewrite <- Pos.add_diag. apply Pos.lt_add_r.
        apply (Pos.lt_trans _ p). apply H0.
        rewrite <- Pos.add_diag. apply Pos.lt_add_r.
        rewrite iterate_succ, iterate_shift, <- itereq. exact des.
      + pose proof (IHp (f x)) as [q [itereq [H H0]]].
        destruct H0.
        2: exfalso; destruct H0; rewrite <- itereq, des in H1; discriminate.
        subst q.
        specialize (IHp (iterate_stop p (f x))) as [q [qeq [H0 H1]]].
        exists (Pos.succ q+p)%positive. split.
        rewrite qeq.
        rewrite <- Pos.add_1_r, <- Pos.add_assoc, iterate_add.
        apply f_equal.
        rewrite Pos.add_1_l, itereq, iterate_succ, iterate_shift.
        reflexivity. split.
        apply (Pos.peano_case
                 (fun r => (r < Pos.succ q+p)%positive → stop (iterate r x) ≡ false)).
        intros. exact des1.
        intros r H2.
        rewrite iterate_succ, iterate_shift.
        destruct (Pos.lt_total r p).
        apply H, H3.
        destruct H3. rewrite H3.
        rewrite <- itereq. exact des.
        rewrite <- (Pplus_minus r p).
        2: apply Pos.lt_gt, H3.
        rewrite Pos.add_comm, iterate_add, <- itereq.
        apply (H0 (r-p)%positive).
        rewrite <- (Pos.add_1_l q), <- Pos.add_assoc, Pos.add_1_l in H2.
        apply Pos.succ_lt_mono in H2.
        rewrite <- (Pplus_minus r p) in H2.
        2: apply Pos.lt_gt, H3.
        rewrite Pos.add_comm in H2.
        apply Pos.add_lt_mono_r in H2. exact H2.
        destruct H1. left. rewrite H1.
        rewrite Pos.xI_succ_xO.
        rewrite <- (Pos.add_1_l q), <- Pos.add_assoc, Pos.add_1_l.
        rewrite Pos.add_diag. reflexivity.
        right. split. rewrite Pos.xI_succ_xO.
        rewrite <- Pos.add_1_l, <- Pos.add_assoc, Pos.add_1_l.
        rewrite <- Pos.succ_lt_mono, <- Pos.add_diag.
        apply Pos.add_lt_mono_r, H1.
        rewrite <- Pos.add_1_r, <- Pos.add_assoc, iterate_add.
        rewrite Pos.add_1_l, iterate_succ, iterate_shift.
        rewrite <- itereq. apply H1.
    - intro x. simpl.
      destruct (stop (iterate_stop p x)) eqn:des.
      + (* Stopped at p by the stop predicate,
           prove that value is the same at 2p. *)
        specialize (IHp x) as [q [itereq [H H0]]].
        exists q. split. exact itereq. split.
        intros. apply H, H1. right.
        split. destruct H0.
        rewrite H0. rewrite <- Pos.add_diag. apply Pos.lt_add_r.
        apply (Pos.lt_trans _ p). apply H0.
        rewrite <- Pos.add_diag. apply Pos.lt_add_r.
        rewrite <- itereq. exact des.
      + pose proof (IHp x) as [q [itereq [H H0]]].
        destruct H0.
        2: exfalso; destruct H0; rewrite <- itereq, des in H1; discriminate.
        subst q.
        specialize (IHp (iterate_stop p x)) as [q [qeq [H0 H1]]].
        exists (q+p)%positive. split.
        rewrite qeq, iterate_add.
        apply f_equal. exact itereq.
        split. intros.
        destruct (Pos.lt_total r p).
        apply H, H3. destruct H3. rewrite H3. clear H3 H2 r.
        rewrite <- itereq. exact des.
        rewrite <- (Pplus_minus r p).
        2: apply Pos.lt_gt, H3.
        rewrite Pos.add_comm, iterate_add, <- itereq.
        apply (H0 (r-p)%positive).
        rewrite <- (Pplus_minus r p) in H2.
        2: apply Pos.lt_gt, H3.
        rewrite Pos.add_comm in H2.
        apply Pos.add_lt_mono_r in H2.
        exact H2.
        destruct H1. left. rewrite H1.
        rewrite Pos.add_diag. reflexivity.
        right. split.
        rewrite <- Pos.add_diag.
        apply Pos.add_lt_mono_r, H1.
        rewrite iterate_add, <- itereq. apply H1.
    - intro x. exists xH. split. reflexivity.
      split. intros. exfalso; exact (Pos.nlt_1_r r H).
      left. reflexivity.
  Qed.

  Lemma iterate_stop_one : forall (x : X),
      iterate_stop 1 x ≡ f x.
  Proof.
    reflexivity.
  Qed.

  Lemma iterate_stop_indep : forall (p q : positive) (x : X),
      stop (iterate p x) ≡ true
      -> stop (iterate q x) ≡ true
      -> iterate_stop p x ≡ iterate_stop q x.
  Proof.
    intros.
    pose proof (iterate_stop_correct p x) as [r [rpeq [H1 H2]]].
    assert (stop (iterate r x) ≡ true) as rstop.
    { destruct H2. rewrite <- H2. exact H. apply H2. }
    rewrite rpeq. clear H2 rpeq H p.
    pose proof (iterate_stop_correct q x) as [s [sqeq [H H2]]].
    assert (stop (iterate s x) ≡ true) as sstop.
    { destruct H2. rewrite <- H2. exact H0. apply H2. }
    rewrite sqeq. clear H2 sqeq H0 q.
    destruct (Pos.lt_total r s).
    - exfalso. specialize (H r H0).
      rewrite H in rstop. discriminate.
    - destruct H0. rewrite H0. reflexivity.
      exfalso. specialize (H1 s H0).
      rewrite H1 in sstop. discriminate.
  Qed.

  Lemma iterate_stop_unique : forall (p q : positive) (x : X),
      stop (iterate p x) ≡ true
      -> stop (iterate q x) ≡ true
      -> (forall i:positive, Pos.lt i q -> stop (iterate i x) ≡ false)
      -> iterate_stop p x ≡ iterate q x.
  Proof.
    intros.
    pose proof (iterate_stop_correct p x) as [r [rpeq [H2 H3]]].
    rewrite rpeq. replace r with q. reflexivity.
    destruct (Pos.lt_total q r).
    - exfalso. specialize (H2 q H4). rewrite H0 in H2. discriminate.
    - destruct H4. exact H4. exfalso.
      destruct H3.
      + subst r.
        specialize (H1 p H4). rewrite H in H1. discriminate.
      + destruct H3. specialize (H1 r H4).
        rewrite H1 in H5. discriminate.
  Qed.

  Definition CRstream_opp (X:Type) (f : X*Q->X*Q) (xq : X*Q) : X*Q
    := let (x,q) := xq in
       let (y,r) := f (x,-q) in
       (y,-r).

End StreamGenerators.

Lemma CRstream_opp_pth : forall (X:Type) (f : X*Q->X*Q) (xq : X*Q) (p : positive),
    let (y,r) := iterate _ f p xq in
    let (z,s) := iterate _ (CRstream_opp X f) p (let (x,q):=xq in (x,-q)) in
    y ≡ z /\ s ≡ -r.
Proof.
  intros X f xq.
  apply Pos.peano_ind.
  - simpl. destruct xq as [x q].
    unfold CRstream_opp.
    replace (--q) with q. destruct (f (x,q)).
    split; reflexivity.
    destruct q. unfold Qopp; simpl.
    rewrite Z.opp_involutive. reflexivity.
  - intros IHp H.
    rewrite CRstreams.iterate_succ, CRstreams.iterate_succ.
    destruct (iterate _ f IHp xq),
    (iterate _ (CRstream_opp X f) IHp
                       (let (x0, q0) := xq in (x0, - q0))).
    unfold CRstream_opp. destruct H. subst q0. subst x0.
    replace (--q) with q. destruct (f (x,q)).
    split; reflexivity.
    destruct q. unfold Qopp; simpl.
    rewrite Z.opp_involutive. reflexivity.
Qed.


From Undecidability.L.Complexity Require Export UpToC GenericNary.

Require Import smpl.Smpl.
From Coq Require Import Setoid.
From Coq Require Import CRelationClasses CMorphisms.
From Undecidability.Shared.Libs.PSL Require FinTypes.

Local Set Universe Polymorphism.

Lemma leToC_eta X (f g :X -> _) :
  (leUpToC f g) = (leUpToC (fun x => f x) (fun x => g x)).
Proof. reflexivity. Qed.

Smpl Add 2 rewrite leToC_eta in *: nary_prepare.

Set Default Proof Using "Type".

Section workaround.
  (*This makes the apply_nary tactic and the rewrites with leToC_eta and "=" work *)
  Local Generalizable Variables A R eqA B S eqB.

  Global Instance pointwise_reflexive {A} `(reflb : Reflexive B eqB) :
    Reflexive (pointwise_relation A eqB) | 9.
  Proof. firstorder. Qed.
  Global Instance pointwise_symmetric {A} `(symb : Symmetric B eqB) :
    Symmetric (pointwise_relation A eqB) | 9.
  Proof. firstorder. Qed.
  Global Instance pointwise_transitive {A} `(transb : Transitive B eqB) :
    Transitive (pointwise_relation A eqB) | 9.
  Proof. firstorder. Qed.
  Global Instance pointwise_equivalence {A} `(eqb : Equivalence B eqB) :
    Equivalence (pointwise_relation A eqB) | 9.
  Proof. firstorder. Qed.

  Instance workaround1 : @subrelation Type (@eq Type) arrow.
  Proof. cbv. firstorder congruence. Qed.

  Global Instance workaround2 X Y: (subrelation (pointwise_relation X (@eq Y)) (Morphisms.pointwise_relation X eq)).
  Proof. firstorder. Qed.

End workaround.

Lemma upToC_add_nary (domain : list Set) F (f1 f2 : Rarrow domain nat) :
  Uncurry f1 <=c F
  -> Uncurry f2 <=c F
  -> Fun' (fun x => App f1 x + App f2 x) <=c F.
Proof.
  prove_nary upToC_add.
Qed.

Lemma upToC_max_nary (domain : list Set) F (f1 f2 : Rarrow domain nat) :
  Uncurry f1 <=c F
  -> Uncurry f2 <=c F
  -> Fun' (fun x => max (App f1 x) (App f2 x)) <=c F.
Proof.
  prove_nary upToC_max.
Qed.

Lemma upToC_min_nary (domain : list Set) F (f1 f2 : Rarrow domain nat) :
  Uncurry f1 <=c F
  -> Uncurry f2 <=c F
  -> Fun' (fun x => min (App f1 x) (App f2 x)) <=c F.
Proof.
  prove_nary upToC_min.
Qed.

Lemma upToC_mul_c_l_nary (domain : list Set)c F  (f : Rarrow domain nat):
  Uncurry f <=c F
  -> Fun' (fun x => c * App f x) <=c F.
Proof.
  prove_nary upToC_mul_c_l.
Qed.

Lemma upToC_mul_c_r_nary (domain : list Set)  c F (f : Rarrow domain nat):
  Uncurry f <=c F -> Fun'(fun x => App f x * c) <=c F.
Proof.
  prove_nary upToC_mul_c_r.
Qed.

Lemma upToC_c_nary (domain : list Set) c F:
  (fun _ => 1) <=c F ->
  Const' domain c <=c F.
Proof.
  prove_nary upToC_c.
Qed.

Lemma upToC_S_nary (domain : list Set) F (f : Rarrow domain nat) :
  Const' domain 1 <=c F
  -> Uncurry f <=c F
  -> Fun' (fun x => S (App f x)) <=c F.
Proof.
  prove_nary upToC_S.
Qed.

Lemma upToC_mul_nary (domain : list Set) (F1 F2 f1 f2 : Rarrow domain nat) :
  Uncurry f1 <=c Uncurry F1
  -> Uncurry f2 <=c Uncurry F2
  -> Fun' (fun x => App f1 x * App f2 x) <=c Fun' (fun x => App F1 x * App F2 x).
Proof.
  prove_nary upToC_mul.
Qed.

Lemma upToC_pow_r_drop_nary domain c f (F : Rarrow domain nat) :
  0 < c
  -> f <=c Uncurry F
  -> f <=c Fun' (fun x => (App F x) ^ c).
Proof.
  now prove_nary upToC_pow_r_drop.
Qed.

Lemma upToC_pow_le_compat_nary domain c c' (f f' : Rarrow domain nat) :
  0 < c -> c <= c'
  -> Uncurry f <=c Uncurry f'
  -> Fun' (fun x => (App f x) ^ c) <=c Fun' (fun x => (App f' x) ^ c').
Proof.
  now prove_nary upToC_pow_le_compat.
Qed.

(* Applying n-ary leUpToC lemmas *)

Ltac domain_of_prod S :=
  let S := constr:(S) in
  let S := eval simpl in S in
  list_of_tuple S.

Ltac leUpToC_domain G :=
  match G with
  | @leUpToC ?F _ _ =>
    let L := domain_of_prod F in
    let L := constr:(L) in
    exact (Mk_domain_of_goal L)
  end.

#[export] Hint Extern 0 Domain_of_goal => (mk_domain_getter leUpToC_domain) : domain_of_goal.

Smpl Add 6 first [nary simple apply upToC_add_nary | nary simple apply upToC_mul_c_l_nary | nary simple apply upToC_mul_c_r_nary
                  | nary simple apply upToC_max_nary| nary simple apply upToC_min_nary
                  | progress (nary simple apply upToC_c_nary) | _applyIfNotConst_nat (nary simple apply upToC_S_nary)] : upToC.

Ltac destruct_pair_rec p :=
  lazymatch type of p with
    (_*_)%type=> let lhs := fresh "p" in
            let x := fresh "x" in
            destruct p as [lhs x];destruct_pair_rec lhs
  | _ => idtac
  end.

Ltac upToC_le_nary_solve :=
  let x := fresh "x" in
  apply upToC_le;intros x;destruct_pair_rec x; first [nia|lia].

Smpl Add upToC_le_nary_solve : upToC_solve.

Goal
  @leUpToC (nat*bool*nat)
  (fun '(xxx,y,z) => xxx+2+3*z) (fun '(x,y,z) => x+z+1).
Proof.
  smpl_upToC_solve.
Qed.

Goal (fun '(x,y) => S x + 3 + S y) <=c (fun '(x,y) => x+y+1).
Proof.
  timeout 20 (smpl_upToC_solve).
Qed.

Goal (fun '(x,y) => 3) <=c (fun '(x,y) => x+y+1).
Proof.
  smpl upToC. smpl upToC_solve.
Qed.

Section bla.
  Import FinTypes.
  Lemma leUpToC_finCases_nary domain (Y:FinTypes.finType) Z__case (cases : forall (y:Y), Z__case y -> Rtuple domain) (f : Rarrow domain nat) (F : Rtuple domain -> nat) :
    (forall x, exists y (z : Z__case y), cases y z = x)
    -> (forall y, (fun z => App f (cases y z)) <=c (fun z => F (cases y z)))
    -> Fun' (fun x => App f x) <=c F.
  Proof.
    prove_nary leUpToC_finCases.
  Qed.
End bla.


Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Essentials.HoTT_Facts.
Require Import Category.Main.
Require Import Basic_Cons.Terminal.
Require Import Coq_Cats.Type_Cat.Type_Cat.

Local Obligation Tactic := program_simpl; auto 3.

(** The empty type is the initial object of category of types. *)
Program Definition Empty_init : Initial Type_Cat.
Proof.
  refine
    (
      @Build_Terminal
        ((Type_Cat)^op)
        (@BuildTruncType _ _ Empty_HSet)
        _
        _
    ); cbn; auto.
Defined.


Require Import Coq.ZArith.ZArith.
Require Import Coq.micromega.Lia.
Require Import Coq.Lists.List.
Require Import Optimizer.Machine.
Require Import Optimizer.ProofOfConcept.Enumerators.
Require Import Optimizer.ProofOfConcept.Instructions.
Require Import Optimizer.ProofOfConcept.Registers.
Require Import Optimizer.ProofOfConcept.Glue.
Import Machine.
Local Open Scope Z_scope.

Module All.
  Definition rep (ap : abstract_program) (p : program) : Prop := to_abstract p = ap.
  Definition rep_enum := (enumerate_concrete instr_size).
  Lemma rep_enum_complete t p : valid p -> rep t p -> In p (rep_enum t).
  Proof.
    cbv [rep rep_enum]. intros; subst.
    eapply enumerate_concrete_complete; eauto;
      apply precondition_length_args || apply precondition_instr_size.
  Qed.
  Lemma rep_enum_sound t p : In p (rep_enum t) -> rep t p.
  Proof.
    cbv [rep rep_enum]. intros.
    erewrite enumerate_concrete_to_abstract by eassumption.
    reflexivity.
  Qed.

  Definition candidates p := enumerate_under_cost instr_cost (cost p).
  Lemma candidates_complete p_spec op :
    optimal op ->
    equivalent p_spec op ->
    (cost op < cost p_spec)%nat ->
    exists t,
      rep t op /\ In t (candidates p_spec).
  Proof.
    intros. exists (to_abstract op).
    split; [reflexivity|]. cbv [candidates].
    eapply enumerate_under_cost_complete;
      eauto using instr_cost_pos, all_instructions_complete.
    intros; cbn; lia.
  Qed.

  Lemma optimal_limited_domain_equiv p_spec :
    valid p_spec ->
    Forall (fun ap => forall p' : program, rep ap p' -> valid p' -> ~ p_spec == p') (candidates p_spec) ->
    optimal p_spec.
  Proof.
    intros. pose proof (optimal_limited_domain_equiv rep).
    eauto using rep_enum_complete, rep_enum_sound, candidates_complete.
  Qed.
End All.


Require Import SetoidClass SetoidCat Algebra.SetoidCat.MaybeUtils Tactics Monoid Pointed Algebra.Pointed.Maybe.

Section Maybe_First_Monoid.
  Definition _maybe_first_mappend {C} {CS : Setoid C}  (a b : maybe C) : maybe C :=
    match a with
      | None => b
      | Some a' => a
    end
  .

  Instance _maybe_first_mappend_Proper {C} {CS : Setoid C}  : Proper (equiv ==> equiv ==> equiv) _maybe_first_mappend.
  Proof.
    autounfold. intros. unfold _maybe_first_mappend. matchequiv. auto. auto.
  Qed.

  Definition maybe_first_mappend {C} {CS : Setoid C} : maybeS CS ~> maybeS CS ~~> maybeS CS := injF2 _maybe_first_mappend _.

  Instance maybe_mappend_PointedFunction2 A AS : PointedFunction2 (@maybe_first_mappend A AS).
  Proof.
    split. simpl. auto.
  Qed.

  Instance maybe_first_Monoid {C} {CS : Setoid C} : @Monoid (maybe C) _.
  Proof.
    exists (None) (maybe_first_mappend).
    intros. simpl. destruct a. reflexivity. reflexivity.
    intros. destruct a. simpl. reflexivity. simpl. auto.
    intros. destruct a. simpl. reflexivity. destruct b. simpl. reflexivity. simpl. destruct c.  reflexivity. reflexivity.
  Defined.

End Maybe_First_Monoid.

Section Maybe_A_Monoid.
  Definition _maybe_mappend {C} {CS : Setoid C} {mon : @Monoid C CS} (a b : maybe C) : maybe C :=
    match a with
      | None => b
      | Some a' => match b with
                     | None => a
                     | Some b' => Some (mappend @ a' @ b')
                   end
    end
  .

  Instance _maybe_mappend_Proper {C} {CS : Setoid C} {mon : @Monoid C CS} : Proper (equiv ==> equiv ==> equiv) _maybe_mappend.
  Proof.
    autounfold. intros. unfold _maybe_mappend. matchequiv. matchequiv. simpl in *. rewritesr.  auto. auto.
  Qed.

  Definition maybe_mappend {C} {CS : Setoid C} {mon : @Monoid C CS}: maybeS CS ~> maybeS CS ~~> maybeS CS := injF2 _maybe_mappend _.

  Instance maybe_A_Monoid {C} {CS : Setoid C} {mon : @Monoid C CS}: @Monoid (maybe C) _.
  Proof.
    exists (None) (maybe_mappend).
    intros. simpl. reflexivity.
    intros. simpl. destruct a. simpl. reflexivity. simpl. auto.
    intros. simpl. destruct a. simpl. destruct b. simpl. destruct c. rewrite associativity_monoid. reflexivity. reflexivity. destruct c. simpl. reflexivity. simpl. reflexivity. destruct b. simpl. destruct c. reflexivity. reflexivity. destruct c. simpl. reflexivity. simpl. auto.
  Defined.
End Maybe_A_Monoid.