(** * Tactics: More Basic Tactics *)

(** This chapter introduces several additional proof strategies
    and tactics that allow us to begin proving more interesting
    properties of functional programs.

    We will see:
    - how to use auxiliary lemmas in both "forward-" and
      "backward-style" proofs;
    - how to reason about data constructors -- in particular, how to
      use the fact that they are injective and disjoint;
    - how to strengthen an induction hypothesis, and when such
      strengthening is required; and
    - more details on how to reason by case analysis. *)

Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
From LF Require Export Poly.

(* ################################################################# *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    _exactly_ the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m : nat),
  n = m ->
  n = m.
Proof.
  intros n m eq.

(** Here, we could finish with "[rewrite -> eq.  reflexivity.]" as we
    have done several times before.  Alternatively, we can finish in
    a single step by using the [apply] tactic: *)

  apply eq.
Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
  n = m ->
  (n = m -> [n;o] = [m;p]) ->
  [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.
Qed.

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that introduces some _universally quantified
    variables_.  When Coq matches the current goal against the
    conclusion of [H], it will try to find appropriate values for
    these variables.  For example, when we do [apply eq2] in the
    following proof, the universal variable [q] in [eq2] gets
    instantiated with [n], and [r] gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
  (n,n) = (m,m)  ->
  (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
  [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.
Qed.

(** **** Exercise: 2 stars, standard, optional (silly_ex)

    Complete the following proof using only [intros] and [apply]. *)
Theorem silly_ex : forall p,
  (forall n, even n = true -> even (S n) = false) ->
  (forall n, even n = false -> odd n = true) ->
  even p = true ->
  odd (S p) = true.
Proof.
  intros p H1 H2 H3. apply H2. apply H1. apply H3.
Qed.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal exactly -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3 : forall (n m : nat),
  n = m ->
  m = n.
Proof.
  intros n m H.

  (** Here we cannot use [apply] directly... *)

  Fail apply H.

  (** but we can use the [symmetry] tactic, which switches the left
     and right sides of an equality in the goal. *)

  symmetry. apply H.
Qed.

(** **** Exercise: 3 stars, standard (apply_exercise1)

    _Hint_: You can also use [apply] with previously defined lemmas,
    not just hypotheses in the context.  You may find earlier lemmas
    like [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],
    etc. helpful.  Also, remember that [Search] is your friend (though
    it may not find earlier lemmas if they were posed as optional
    problems and you chose not to finish the proofs). *)

Search rev.

Theorem rev_exercise1 : forall (l l' : list nat),
  l = rev l' ->
  l' = rev l.
Proof.
  intros l l' H. rewrite H. symmetry. apply rev_involutive.
Qed.
(** [] *)

(** **** Exercise: 1 star, standard, optional (apply_rewrite)

    Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied? *)

(* FILL IN HERE

    [] *)

(* ################################################################# *)
(** * The [apply with] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a;b]] to [[e;f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.
Qed.

(** Since this is a common pattern, we might like to pull it out as a
    lemma that records, once and for all, the fact that equality is
    transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
  reflexivity.
Qed.

(** Now, we should be able to use [trans_eq] to prove the above
    example.  However, to do this we need a slight refinement of the
    [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.

(** If we simply tell Coq [apply trans_eq] at this point, it can
    tell (by matching the goal against the conclusion of the lemma)
    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
    [o] with [[e,f]].  However, the matching process doesn't determine
    an instantiation for [m]: we have to supply one explicitly by
    adding "[with (m:=[c,d])]" to the invocation of [apply]. *)

  apply trans_eq with (m:=[c;d]).
  apply eq1. apply eq2.   Qed.

(** Actually, the name [m] in the [with] clause is not required,
    since Coq is often smart enough to figure out which variable we
    are instantiating. We could instead simply write [apply trans_eq
    with [c;d]]. *)

(** Coq also has a built-in tactic [transitivity] that
    accomplishes the same purpose as applying [trans_eq]. The tactic
    requires us to state the instantiation we want, just like [apply
    with] does. *)

Example trans_eq_example'' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  transitivity [c;d].
  apply eq1. apply eq2.
Qed.

(** **** Exercise: 3 stars, standard, optional (trans_eq_exercise) *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros n m o p H1 H2. transitivity m. apply H2. apply H1.
Qed.
(** [] *)

(* ################################################################# *)
(** * The [injection] and [discriminate] Tactics *)

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O
       | S (n : nat).

    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition are two
    additional facts:

    - The constructor [S] is _injective_ (or _one-to-one_).  That is,
      if [S n = S m], it must be that [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n]. *)

(** Similar principles apply to every inductively defined type:
    all constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since [true] and
    [false] take no arguments, their injectivity is neither here nor
    there.)  And so on. *)

(** We can _prove_ the injectivity of [S] by using the [pred] function
    defined in [Basics.v]. *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  assert (H2: n = pred (S n)). { reflexivity. }
  rewrite H2. rewrite H1. simpl. reflexivity.
Qed.

(** This technique can be generalized to any constructor by
    writing the equivalent of [pred] -- i.e., writing a function that
    "undoes" one application of the constructor.

    As a more convenient alternative, Coq provides a tactic called
    [injection] that allows us to exploit the injectivity of any
    constructor.  Here is an alternate proof of the above theorem
    using [injection]: *)

Theorem S_injective' : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [injection H as Hmn] at this point, we are asking Coq
    to generate all equations that it can infer from [H] using the
    injectivity of constructors (in the present example, the equation
    [n = m]). Each such equation is added as a hypothesis (with the
    name [Hmn] in this case) into the context. *)

  injection H as Hnm. apply Hnm.
Qed.

(** Here's a more interesting example that shows how [injection] can
    derive multiple equations at once. *)

Theorem injection_ex1 : forall (n m o : nat),
  [n;m] = [o;o] ->
  n = m.
Proof.
  intros n m o H.
  (* WORKED IN CLASS *)
  injection H as H1 H2.
  (* Could also be done by transitivity, sooooo much possibilities ! *)
  rewrite H1. rewrite H2. reflexivity.
Qed.

Search list.

(** **** Exercise: 3 stars, standard (injection_ex3) *)
Example injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  intros X x y z l j H1 H2. injection H1 as H3 H4. assert (y::l = z::l).
    + transitivity j. apply H4. apply H2.
    + injection H as H5. transitivity z. apply H3. symmetry. apply H5.
Qed.
(** [] *)

(** So much for injectivity of constructors.  What about disjointness? *)

(** The principle of disjointness says that two terms beginning
    with different constructors (like [O] and [S], or [true] and [false])
    can never be equal.  This means that, any time we find ourselves
    in a context where we've _assumed_ that two such terms are equal,
    we are justified in concluding anything we want, since the
    assumption is nonsensical. *)

(** The [discriminate] tactic embodies this principle: It is used on a
    hypothesis involving an equality between different
    constructors (e.g., [false = true]), and it solves the current
    goal immediately.  Some examples: *)

Theorem discriminate_ex1 : forall (n m : nat),
  false = true ->
  n = m.
Proof.
  intros n m contra. discriminate contra.
Qed.

Theorem discriminate_ex2 : forall (n : nat),
  S n = O ->
  2 + 2 = 5.
Proof.
  intros n contra. discriminate contra.
Qed.

(** These examples are instances of a logical principle known as the
    _principle of explosion_, which asserts that a contradictory
    hypothesis entails anything (even manifestly false things!). *)

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, _if_ the
    nonsensical situation described by the premise did somehow arise,
    _then_ the nonsensical conclusion would also follow, because we'd
    be living in an inconsistent universe where every statement is
    true.  We'll explore the principle of explosion in more detail in
    the next chapter. *)

(** **** Exercise: 1 star, standard (discriminate_ex3) *)
Example discriminate_ex3 :
  forall (X : Type) (x y z : X) (l j : list X),
    x :: y :: l = [] ->
    x = z.
Proof.
  intros X x y z l j Habsrd. discriminate Habsrd.
Qed.
(** [] *)

(** For a slightly more involved example, we can use [discriminate] to
    make a connection between the two different notions of
    equality ([=] and [=?]) on natural numbers. *)
Theorem eqb_0_l : forall n,
   0 =? n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'] eqn:E.
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming [0
    =? (S n') = true], we must show [S n' = 0]!  The way forward is to
    observe that the assumption itself is nonsensical: *)

  - (* n = S n' *)
    simpl.

(** If we use [discriminate] on this hypothesis, Coq confirms
    that the subgoal we are working on is impossible and removes it
    from further consideration. *)

    intros H. discriminate H.
Qed.

(** The injectivity of constructors allows us to reason that
    [forall (n m : nat), S n = S m -> n = m].  The converse of this
    implication is an instance of a more general fact about both
    constructors and functions, which we will find convenient in a few
    places below: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.

Theorem eq_implies_succ_equal : forall (n m : nat),
  n = m -> S n = S m.
Proof.
  intros n m H. apply f_equal. apply H.
Qed.

(** There is also a tactic named `f_equal` that can prove such
    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],
    the tactic [f_equal] will produce subgoals of the form [f = g],
    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals
    that are simple enough (e.g., immediately provable by
    [reflexivity]) will be automatically discharged by [f_equal]. *)

Theorem eq_implies_succ_equal' : forall (n m : nat),
  n = m -> S n = S m.
Proof.
  intros n m H. f_equal. apply H.
Qed.

(* ################################################################# *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic "[simpl in H]" performs simplification on
    the hypothesis [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
  ((S n) =? (S m)) = b  ->
  (n =? m) = b.
Proof.
  intros n m b H. simpl in H. apply H.
Qed.

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [X -> Y], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [Y] into a subgoal [X]), [apply L in H] matches [H]
    against [X] and, if successful, replaces it with [Y].

    In other words, [apply L in H] gives us a form of "forward
    reasoning": given [X -> Y] and a hypothesis matching [X], it
    produces a hypothesis matching [Y].

    By contrast, [apply L] is "backward reasoning": it says that if we
    know [X -> Y] and we are trying to prove [Y], it suffices to prove
    [X].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly4 : forall (n m p q : nat),
  (n = m -> p = q) ->
  m = n ->
  q = p.
Proof.
  intros n m p q EQ H.
  symmetry in H. apply EQ in H. symmetry in H.
  apply H.
Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_ and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.

    The informal proofs that you've seen in math or computer science
    classes probably tended to use forward reasoning.  In general,
    idiomatic use of Coq favors backward reasoning, but in some
    situations the forward style can be easier to think about. *)

(* ################################################################# *)
(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we sometimes need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that [double] is injective -- i.e., that it maps
    different arguments to different results:

       Theorem double_injective: forall n m,
         double n = double m -> n = m.

    The way we start this proof is a bit delicate: if we begin it with

       intros n. induction n.

    all is well.  But if we begin it with introducing both variables

       intros n m. induction n.

    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n m. induction n as [| n' IHn'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.
  - (* n = S n' *) intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) discriminate eq.
    + (* m = S m' *) apply f_equal.

(** At this point, the induction hypothesis ([IHn']) does _not_ give us
    [n' = m'] -- there is an extra [S] in the way -- so the goal is
    not provable. *)

Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _these particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition

      - [P n] = "if [double n = double m], then [n = m]"

    holds, by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]") and

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular (arbitrary,
    but fixed) [m] -- say, [5].  The statement is then saying that,
    if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help at all with proving
    [R]!  If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing
    helpful about whether [double n] is [10] (indeed, it strongly
    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)

(** Trying to carry out this proof by induction on [n] when [m] is
    already in the context doesn't work because we are then trying to
    prove a statement involving _every_ [n] but just a _single_ [m]. *)

(** A successful proof of [double_injective] leaves [m] universally
    quantified in the goal statement at the point where the
    [induction] tactic is invoked on [n]: *)

Theorem double_injective : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n. induction n as [| n' IHn'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.

  - (* n = S n' *)

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., we must prove the statement for _every_ [m]), but
    the IH is correspondingly more flexible, allowing us to choose any
    [m] we like when we apply the IH. *)

    intros m eq.

(** Now we've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'] eqn:E.
    + (* m = O *)

(** The 0 case is trivial: *)

    discriminate eq.
    + (* m = S m' *)
      apply f_equal.

(** At this point, since we are in the second branch of the [destruct
    m], the [m'] mentioned in the context is the predecessor of the
    [m] we started out talking about.  Since we are also in the [S]
    branch of the induction, this is perfect: if we instantiate the
    generic [m] in the IH with the current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.

(** What you should take away from all this is that you need to be
    careful, when using induction, that you are not trying to prove
    something too specific: When proving a property involving two
    variables [n] and [m] by induction on [n], it is sometimes crucial
    to leave [m] generic. *)

(** The following exercise (which further strengthens the link between
    [=?] and [=]) follows the same pattern. *)

(** **** Exercise: 2 stars, standard (eqb_true) *)
Theorem eqb_true : forall n m,
  n =? m = true -> n = m.
Proof.
  intros n. induction n as [|n' H'].
    - intros m. simpl. destruct m as [|m'].
        + reflexivity.
        + discriminate.
    - intros m. destruct m as [|m'].
        + simpl. discriminate.
        + intros H. simpl in H. apply H' in H. rewrite H. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (eqb_true_informal)

    Give a careful informal proof of [eqb_true], being as explicit
    as possible about quantifiers. *)

(*
  Generic case: Suppose that for a given n, forall m:nat n=?m = true -> n = m,
      let us proove that, then, forall m: nat, S n =? m = true -> S n = m
      Given m:nat, m is either O or S m' with m':nat. S n = O is absurd.
      S n =? S m' can be simplified to n =? m', therefore we have n =? m' = true
      by hypothesis, we have n = m', therefore S n = S m' = m
   Origin case: Now let us proov that the hypothesis is true for the first natural, i.e. that
      forall m: nat, O =? m = true -> O = m
      for a given m, m is either O or S m' with m':nat
      if m = O then the hypothesis is trivial
       if m = S m' then O =? m = false, so the hypothesis becoms false = true, which is absurd.
   Qed.
*)

(* Do not modify the following line: *)
Definition manual_grade_for_informal_proof : option (nat*string) := None.
(** [] *)

(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective)

    In addition to being careful about how you use [intros], practice
    using "in" variants in this proof.  (Hint: use [plus_n_Sm].) *)
Search S.
Theorem plus_n_n_injective : forall n m,
  n + n = m + m ->
  n = m.
Proof.
  intros n. induction n as [|n' H'].
    - simpl. intros m H. rewrite H. destruct m as [|m']. reflexivity. discriminate H.
    - simpl. intros m H. destruct m as [|m']. discriminate H.
        rewrite <- (plus_n_Sm (S m') m') in H.
        apply eq_add_S in H.
        rewrite <- plus_n_Sm in H.
        rewrite (add_comm (S m') m') in H. rewrite <- plus_n_Sm in H.
        apply eq_add_S in H.
        apply H' in H. rewrite H. reflexivity.
Qed.
(** [] *)

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    some _rearrangement_ of quantified variables is needed.  Suppose,
    for example, that we wanted to prove [double_injective] by
    induction on [m] instead of [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n m. induction m as [| m' IHm'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
        (* We are stuck here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (And if we simply say [induction m] without
    introducing anything first, Coq will automatically introduce [n]
    for us!)  *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables out of the context and putting them
    back at the beginning of the goal.  The [generalize dependent]
    tactic does this. *)

Theorem double_injective_take2 : forall n m,
  double n = double m ->
  n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m' IHm'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. injection eq as goal. apply goal. Qed.

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

    _Theorem_: For any nats [n] and [m], if [double n = double m], then
      [n = m].

    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
      any [n], if [double n = double m] then [n = m].

      - First, suppose [m = 0], and suppose [n] is a number such
        that [double n = double m].  We must show that [n = 0].

        Since [m = 0], by the definition of [double] we have [double n =
        0].  There are two cases to consider for [n].  If [n = 0] we are
        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']
        for some [n'], we derive a contradiction: by the definition of
        [double], we can calculate [double n = S (S (double n'))], but
        this contradicts the assumption that [double n = 0].

      - Second, suppose [m = S m'] and that [n] is again a number such
        that [double n = double m].  We must show that [n = S m'], with
        the induction hypothesis that for every number [s], if [double s =
        double m'] then [s = m'].

        By the fact that [m = S m'] and the definition of [double], we
        have [double n = S (S (double m'))].  There are two cases to
        consider for [n].

        If [n = 0], then by definition [double n = 0], a contradiction.

        Thus, we may assume that [n = S n'] for some [n'], and again by
        the definition of [double] we have [S (S (double n')) =
        S (S (double m'))], which implies by injectivity that [double n' =
        double m'].  Instantiating the induction hypothesis with [n'] thus
        allows us to conclude that [n' = m'], and it follows immediately
        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just
        what we wanted to show. [] *)

(** **** Exercise: 3 stars, standard, especially useful (gen_dep_practice)

    Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
  length l = n ->
  nth_error l n = None.
Proof.
  intros n X l. generalize dependent n.
  induction l as [|h t Hl].
    - intros H. simpl. reflexivity.
    - intros n H. simpl. destruct n as [|n'].
      + discriminate H.
      + simpl in H. apply eq_add_S in H. apply Hl. apply H.
Qed.
(** [] *)

(* ################################################################# *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a name that
    has been introduced by a [Definition] so that we can manipulate
    the expression it denotes.  For example, if we define... *)

Definition square n := n * n.

(** ... and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we appear to be stuck: [simpl] doesn't simplify anything, and
    since we haven't proved any other facts about [square], there is
    nothing we can [apply] or [rewrite] with. *)

(** To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these it is not hard
    to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
    { rewrite mul_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, some deeper discussion of unfolding and
    simplification is in order.

    We already have observed that tactics like [simpl], [reflexivity],
    and [apply] will often unfold the definitions of functions
    automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

(** .... then the [simpl] in the following proof (or the
    [reflexivity], if we omit the [simpl]) will unfold [foo m] to
    [(fun x => 5) m] and then further simplify this expression to just
    [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** But this automatic unfolding is somewhat conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  It is not smart enough to notice that the
    two branches of the [match] are identical, so it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that cannot itself be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone. *)

(** At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m eqn:E.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress. *)

(** A more straightforward way forward is to explicitly tell Coq to
    unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m eqn:E.
  - reflexivity.
  - reflexivity.
Qed.

(* ################################################################# *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  Sometimes we
    need to reason by cases on the result of some _expression_.  We
    can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if n =? 3 then false
  else if n =? 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (n =? 3) eqn:E1.
    - (* n =? 3 = true *) reflexivity.
    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.
      + (* n =? 5 = true *) reflexivity.
      + (* n =? 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (n =? 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (eqb
    n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c]. *)

(** **** Exercise: 3 stars, standard (combine_split)

    Here is an implementation of the [split] function mentioned in
    chapter [Poly]: *)

Fixpoint split {X Y : Type} (l : list (X*Y))
               : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (x, y) :: t =>
      match split t with
      | (lx, ly) => (x :: lx, y :: ly)
      end
  end.

(** Prove that [split] and [combine] are inverses in the following
    sense: *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y l. induction l as [|h t Hl].
    - simpl. intros l1 l2 H. injection H. intros H' H''. rewrite <- H'. rewrite <- H''. reflexivity.
    - intros l1 l2. intros H. destruct h eqn:Hh. simpl in H. destruct (split t) eqn: Hsp. injection H.
      intros Hy Hx. rewrite <- Hy. rewrite <- Hx. simpl. rewrite Hl. reflexivity. reflexivity.
Qed.
(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional; although
    we've chosen to include it most of the time, for the sake of
    documentation, it can often be omitted without harm.

    However, when [destruct]ing compound expressions, the information
    recorded by the [eqn:] can actually be critical: if we leave it
    out, then [destruct] can erase information we need to complete a
    proof.

    For example, suppose we define a function [sillyfun1] like
    this: *)

Definition sillyfun1 (n : nat) : bool :=
  if n =? 3 then true
  else if n =? 5 then true
  else false.

(** Now suppose that we want to convince Coq that [sillyfun1 n]
    yields [true] only when [n] is odd.  If we start the proof like
    this (with no [eqn:] on the [destruct])... *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
  sillyfun1 n = true ->
  odd n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3).
  (* stuck... *)
Abort.

(** ... then we are stuck at this point because the context does
    not contain enough information to prove the goal!  The problem is
    that the substitution performed by [destruct] is quite brutal --
    in this case, it throws away every occurrence of [n =? 3], but we
    need to keep some memory of this expression and how it was
    destructed, because we need to be able to reason that, since [n =?
    3 = true] in this branch of the case analysis, it must be that [n
    = 3], from which it follows that [n] is odd.

    What we want here is to substitute away all existing occurrences of
    [n =? 3], but at the same time add an equation to the context that
    records which case we are in.  This is precisely what the [eqn:]
    qualifier does. *)

Theorem sillyfun1_odd : forall (n : nat),
  sillyfun1 n = true ->
  odd n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (n =? 3) eqn:Heqe3.
  (** Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply eqb_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (** When we come to the second equality test in the body
        of the function we are reasoning about, we can use
        [eqn:] again in the same way, allowing us to finish the
        proof. *)
      destruct (n =? 5) eqn:Heqe5.
        + (* e5 = true *)
          apply eqb_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) discriminate eq.  Qed.

(** **** Exercise: 2 stars, standard (destruct_eqn_practice) *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f b. destruct b eqn:Hb.
    + destruct (f true) eqn: Hft.
      - rewrite Hft. rewrite Hft. reflexivity.
      - destruct (f false) eqn: Hff.
        { apply Hft. }
        { apply Hff. }
    + destruct (f false) eqn: Hff.
      - destruct (f true) eqn: Hft.
        { apply Hft. }
        { apply Hff. }
      - rewrite Hff. rewrite Hff. reflexivity.
Qed.
(** [] *)

(* ################################################################# *)
(** * Review *)

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  But basically we've got what we need to
    get work done.

    Here are the ones we've seen:

      - [intros]: move hypotheses/variables from goal to context

      - [reflexivity]: finish the proof (when the goal looks like [e =
        e])

      - [apply]: prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]: apply a hypothesis, lemma, or constructor to
        a hypothesis in the context (forward reasoning)

      - [apply... with...]: explicitly specify values for variables
        that cannot be determined by pattern matching

      - [simpl]: simplify computations in the goal

      - [simpl in H]: ... or a hypothesis

      - [rewrite]: use an equality hypothesis (or lemma) to rewrite
        the goal

      - [rewrite ... in H]: ... or a hypothesis

      - [symmetry]: changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]: changes a hypothesis of the form [t=u] into
        [u=t]

      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,
        [x=y] and [y=z]

      - [unfold]: replace a defined constant by its right-hand side in
        the goal

      - [unfold... in H]: ... or a hypothesis

      - [destruct... as...]: case analysis on values of inductively
        defined types

      - [destruct... eqn:...]: specify the name of an equation to be
        added to the context, recording the result of the case
        analysis

      - [induction... as...]: induction on values of inductively
        defined types

      - [injection... as...]: reason by injectivity on equalities
        between values of inductively defined types

      - [discriminate]: reason by disjointness of constructors on
        equalities between values of inductively defined types

      - [assert (H: e)] (or [assert (e) as H]): introduce a "local
        lemma" [e] and call it [H]

      - [generalize dependent x]: move the variable [x] (and anything
        else that depends on it) from the context back to an explicit
        hypothesis in the goal formula

      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)

(* ################################################################# *)
(** * Additional Exercises *)

(** **** Exercise: 3 stars, standard (eqb_sym) *)
Theorem eqb_sym : forall (n m : nat),
  (n =? m) = (m =? n).
Proof.
  intros n. induction n as [|n' H'].
    - intros m. simpl. destruct m as [|m'].
      + reflexivity.
      + reflexivity.
    - intros m. simpl. destruct m as [|m'].
      + reflexivity.
      + simpl. apply H'.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)

    Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [(n =? m) = (m =? n)].

   Proof: *)
   (* FILL IN HERE

    [] *)

(** **** Exercise: 3 stars, standard, optional (eqb_trans) *)

Lemma eq_impl_eqb: forall n m,
  n = m -> n =? m = true.
Proof.
  intros n m H. rewrite H. simpl. apply eqb_refl.
Qed.

Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  intros n m p H H'. apply eqb_true in H. apply eqb_true in H'.
  assert (n = p) as H''.
  transitivity m.
      apply H.
      apply H'.
    apply eq_impl_eqb in H''. apply H''.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)

    We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)

Lemma len_0_impl_nil: forall (X: Type) (l: list(X)),
    length l = 0 -> l = [].
Proof.
  intros X l H. destruct l as [|h t] eqn:Hl.
    - reflexivity.
    - discriminate.
Qed.

Definition split_combine_statement : Prop := forall (X: Type) (l1 l2: list(X)),
    length l1 = length l2 -> split(combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
      intros X l1. induction l1 as [|h t Hl1].
        - simpl. intros l2 H. symmetry in H. apply len_0_impl_nil in H. rewrite H. reflexivity.
        - intros l2 H. simpl. destruct l2 as [|h' t'].
          + discriminate H.
          + simpl in H. apply eq_add_S in H. apply Hl1 in H. simpl. rewrite H. reflexivity.
Qed.

(* Do not modify the following line: *)
Definition manual_grade_for_split_combine : option (nat*string) := None.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)

    This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Lemma h_a_eq_h_b_impl_a_eq_b: forall (X : Type) (la lb : list(X)) (a b: X),
  a::la = b::lb -> a = b.
Proof.
  intros X la lb a b. destruct la as [|h t] eqn: Ea.
    - intros H. injection H. intros H' H''. apply H''.
    - intros H. injection H. intros H' H''. apply H''.
Qed.

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                                 (x : X) (l lf : list X),
  filter test l = x :: lf ->
  test x = true.
Proof.
  intros X test x l lf. generalize dependent x. generalize dependent lf.
  induction l as [|h t Hl].
    - intros lf x H. discriminate H.
    - intros lf x. simpl. destruct (test h) eqn: Hh.
      + intros H. assert (x = h) as Hx.
        { injection H. intros H' H''. rewrite H''. reflexivity. }
        { rewrite Hx. apply Hh. }
      + apply Hl.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced, especially useful (forall_exists_challenge)

    Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:

      forallb odd [1;3;5;7;9] = true
      forallb negb [false;false] = true
      forallb even [0;2;4;5] = false
      forallb (eqb 5) [] = true

    The second checks whether there exists an element in the list that
    satisfies a given predicate:

      existsb (eqb 5) [0;2;3;6] = false
      existsb (andb true) [true;true;false] = true
      existsb odd [1;0;0;0;0;3] = true
      existsb even [] = false

    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

    Finally, prove a theorem [existsb_existsb'] stating that
    [existsb'] and [existsb] have the same behavior.
*)

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => true
  | h::t => if test h then forallb test t else false
  end.

Example test_forallb_1 : forallb odd [1;3;5;7;9] = true.
Proof. reflexivity. Qed.

Example test_forallb_2 : forallb negb [false;false] = true.
Proof. reflexivity. Qed.

Example test_forallb_3 : forallb even [0;2;4;5] = false.
Proof. reflexivity. Qed.

Example test_forallb_4 : forallb (eqb 5) [] = true.
Proof. reflexivity. Qed.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | [] => false
  | h::t => if test h then true else existsb test t
  end.

Example test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.
Proof. reflexivity. Qed.

Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. reflexivity. Qed.

Example test_existsb_3 : existsb odd [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.

Example test_existsb_4 : existsb even [] = false.
Proof. reflexivity. Qed.

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=
  let ntest := fun x => negb (test x) in
    negb (forallb ntest l).

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof.
  intros X test l. induction l as [|h t Hl].
    - simpl. reflexivity.
    - simpl. unfold existsb'. simpl. destruct (test h) eqn: Eth.
      + simpl. reflexivity.
      + simpl. rewrite Hl. unfold existsb'. reflexivity.
Qed.

(** [] *)

(* 2021-08-11 15:08 *)


Require Export Iron.Language.SystemF2r.Ty.
Require Export Iron.Language.SystemF2r.Ki.
Require Export Iron.Language.SystemF2r.Collection.

(* Kinds judgement assigns a kind to a type *)
Inductive KIND : kienv -> ty -> ki -> Prop :=
 | KIConFun
   :  forall ke
   ,  KIND ke (TCon TyConFun) (KFun KData (KFun KData KData))

 | KIConData
   :  forall ke i k
   ,  KIND ke (TCon (TyConData i k)) k

 | KIVar
   :  forall ke i k
   ,  has    i k ke
   -> KIND   ke (TVar i) k

 | KIForall
   :  forall ke ke' t
   ,  also   0 KData ke ke'
   -> KIND   ke' t KData
   -> KIND   ke  (TForall t) KData

 | KIApp
   :  forall ke t1 t2 k11 k12
   ,  KIND   ke t1 (KFun k11 k12)
   -> KIND   ke t2 k11
   -> KIND   ke (TApp t1 t2) k12.
Hint Constructors KIND.

(* Invert all hypothesis that are compound kinding statements. *)
Ltac inverts_kind :=
 repeat
  (match goal with
   | [ H: KIND _ (TCon _)    _  |- _ ] => inverts H
   | [ H: KIND _ (TVar _)    _  |- _ ] => inverts H
   | [ H: KIND _ (TForall _) _  |- _ ] => inverts H
   | [ H: KIND _ (TApp _ _) _   |- _ ] => inverts H
   end).

(* A well kinded type is well formed *)
Lemma kind_wfT
 :  forall ke t k
 ,  KIND ke t k
 -> wfT  (length ke) t.
Proof.
 intros ke t k HK. gen ke k.
 induction t; intros; inverts_kind; eauto.
 eapply WfT_TForall. eapply IHt in H2.
 admit.
Qed.
Hint Resolve kind_wfT.

Lemma kind_wfT_Forall
 :  forall ks ts
 ,  Forall (fun t => KIND ks t KData) ts
 -> Forall (wfT (length ks)) ts.
Proof.
 intros. repeat nforall. eauto.
Qed.
Hint Resolve kind_wfT_Forall.

Lemma kind_wfT_Forall2
 :  forall (ke: kienv) ts ks
 ,  Forall2 (KIND ke) ts ks
 -> Forall (wfT (length ke)) ts.
Proof.
 intros.
 eapply (Forall2_Forall_left (KIND ke)).
 nforall. intros. eauto. eauto.
Qed.
Hint Resolve kind_wfT_Forall2.

(* If a type is well kinded in an empty environment,
   then that type is closed. *)
Lemma kind_empty_is_closed
 :  forall t k
 ,  KIND nil t k
 -> closedT t.
Proof.
 intros. unfold closedT.
 have (@length ki nil = 0).
  rewrite <- H0.
  eapply kind_wfT. eauto.
Qed.
Hint Resolve kind_empty_is_closed.

(* Weakening kind environments. *)
Lemma kind_kienv_insert
 :  forall ke ke' i t k1 k2
 ,  also i k2 ke ke'
 -> KIND ke t k1
 -> KIND ke' (liftTT 1 i t) k1.
Proof.
 intros. gen i ke ke' k1.
 induction t; intros; simpl; inverts_kind; eauto.

 Case "TVar".
  lift_cases; intros; repeat nnat; auto.
  eapply KIVar.

 admit.
 admit.
 admit.
Qed.

 (******
   ** for larger environment use
        type : relation tyenv -> relation env
        kind : relation kienv -> relation env

        type (has i t) env env'
        kind (has i k) env env'

unfold has.
  unfold keAtK in *.
  unfold keKi  in *.
  subst.
  lift_cases; intros; repeat nnat; auto.
  eapply KIVar. unfold keAtK. eauto.
  eapply KIVar. unfold keAtK. eauto.

 Case "TForall".
  unfold keKi in *.
  unfold keK  in *.
  subst.
  eapply KIForall.
  unfold keK in *. eauto.
  rewrite insert_rewind.
  eapply IHt. eauto. auto.
Qed.

Lemma kind_kienv_weaken
 :  forall ke t k1 k2
 ,  KIND  ke         t             k1
 -> KIND (ke :> k2) (liftTT 1 0 t) k1.
Proof.
 intros.
 assert (ke :> k2 = insert 0 k2 ke). simpl.
   destruct ke; auto.
 rewrite H0. eapply kind_kienv_insert.
 unfold keKi. eauto. auto.
Qed.

*****)


(* Contains the code that actually evaluates expressions and commands *)

Require Export Typ.
Require Export Sigma.
Require Export Aexp.
Require Export Exp.
Require Export Commands.

Module Evals.

Fixpoint eval_aexp (a : Aexp) (sigma : state) :=
  match a with
    | ALit a' => a'
    | APlus b c => plus_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | AMinus b c => minus_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | AMult b c => mult_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | ADiv b c => div_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | AExp b c => exp_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | AMod b c => mod_aexplit (eval_aexp b sigma) (eval_aexp c sigma)
    | ANeg b => neg_aexplit (eval_aexp b sigma)
    | AVar i =>
      match (sigma i) with
        | mk_typ _ t =>
          match t with
            | mk_explit_from_aexp a' => a'
            | _ => aexp_error (*error!*)
          end
      end
  end.

Definition aexplit_is_equal (e1 e2: AexpLit): BexpLit :=
  match e1, e2 with
    | aexp_error, _ => bexp_error
    | _, aexp_error => bexp_error
    | mk_aexp_lit q1, mk_aexp_lit q2 =>
      if Qeq_bool q1 q2 then mk_bexp_lit true else mk_bexp_lit false
  end.

Definition aexp_is_equal (e1 e2: Aexp) (sigma: state): BexpLit :=
  aexplit_is_equal (eval_aexp e1 sigma) (eval_aexp e2 sigma).

Fixpoint eval_sexp (e: Sexp) (sigma: state): SexpLit :=
  match e with
    | SLit s => s
    | SConcat s1 s2 =>
      let s1eval := eval_sexp s1 sigma in
      let s2eval := eval_sexp s2 sigma in
        match s1eval, s2eval with
          | sexp_error, _ => sexp_error
          | _, sexp_error => sexp_error
          | mk_sexp_lit str1, mk_sexp_lit str2 =>
            mk_sexp_lit (append str1 str2)
        end
    | SVar i =>
      match (sigma i) with
        | mk_typ _ t =>
          match t with
            | mk_explit_from_sexp s' => s'
            | _ => sexp_error (* error! *)
          end
      end
  end.

Definition sexplit_is_equal (s1 s2: SexpLit): BexpLit :=
  match s1, s2 with
    | mk_sexp_lit s1', mk_sexp_lit s2' => mk_bexp_lit (andb (prefix s1' s2') (EqNat.beq_nat (length s1') (length s2')))
    | _, _ => mk_bexp_lit false
  end.

Definition sexp_is_equal (s1 s2: Sexp) (sigma: state): BexpLit :=
  sexplit_is_equal (eval_sexp s1 sigma) (eval_sexp s2 sigma).

Definition uexp_is_equal (u1 u2: Uexp): BexpLit :=
  match u1, u2 with
    | Uexpid (mk_id s1), Uexpid (mk_id s2) => mk_bexp_lit (andb (prefix s1 s2) (EqNat.beq_nat (length s1) (length s2)))
    | _, _ => mk_bexp_lit false (* TODO: Some plus statements could be equal *)
  end.

Definition bexplit_is_equal (e1 e2: BexpLit): BexpLit :=
  match e1, e2 with
    | bexp_error, _ => bexp_error
    | _, bexp_error => bexp_error
    | mk_bexp_lit b1, mk_bexp_lit b2 => mk_bexp_lit (eqb b1 b2)
  end.

Fixpoint eval_bexp (b: Bexp) (sigma : state) (n: nat) : BexpLit :=
  match n with
    | O => bexp_error (* Too many computations *)
    | S n' =>
      match b with
        | BLit b' => b'
        | BVar i =>
          match (sigma i) with
            | mk_typ _ t =>
              match t with
                | mk_explit_from_bexp b' => b'
                | _ => bexp_error (* error! *)
              end
          end
        | BNot a => match eval_bexp a sigma n' with
            | mk_bexp_lit true => mk_bexp_lit false
            | mk_bexp_lit false => mk_bexp_lit true
            | _ => bexp_error
          end
        | BAnd a b => match (eval_bexp a sigma n', eval_bexp b sigma n') with
            | (mk_bexp_lit true, mk_bexp_lit true) => mk_bexp_lit true
            | (bexp_error, _) => bexp_error
            | (_, bexp_error) => bexp_error
            | _ => mk_bexp_lit false
          end
        | BOr a b => match (eval_bexp a sigma n', eval_bexp b sigma n') with
            | (mk_bexp_lit false, mk_bexp_lit false) => mk_bexp_lit false
            | (bexp_error, _) => bexp_error
            | (_, bexp_error) => bexp_error
            | _ => mk_bexp_lit true
          end
        | BEq e1 e2 => exp_is_equal e1 e2 sigma n'
        | BLt e1 e2 =>
          let eval1 := eval_aexp e1 sigma in
          let eval2 := eval_aexp e2 sigma in
            match eval1, eval2 with
              | aexp_error, _ => bexp_error
              | _, aexp_error => bexp_error
              | mk_aexp_lit q1, mk_aexp_lit q2 =>
                mk_bexp_lit (andb (Qle_bool q1 q2) (negb (Qeq_bool q1 q2)))
            end
        | BGt e1 e2 =>
          let eval1 := eval_aexp e1 sigma in
          let eval2 := eval_aexp e2 sigma in
            match eval1, eval2 with
              | aexp_error, _ => bexp_error
              | _, aexp_error => bexp_error
              | mk_aexp_lit q1, mk_aexp_lit q2 =>
                mk_bexp_lit (andb (Qle_bool q2 q1) (negb (Qeq_bool q1 q2)))
            end
        | BLe e1 e2 =>
          let eval1 := eval_aexp e1 sigma in
          let eval2 := eval_aexp e2 sigma in
            match eval1, eval2 with
              | aexp_error, _ => bexp_error
              | _, aexp_error => bexp_error
              | mk_aexp_lit q1, mk_aexp_lit q2 =>
                mk_bexp_lit (Qle_bool q1 q2)
            end
        | BGe e1 e2 =>
          let eval1 := eval_aexp e1 sigma in
          let eval2 := eval_aexp e2 sigma in
            match eval1, eval2 with
              | aexp_error, _ => bexp_error
              | _, aexp_error => bexp_error
              | mk_aexp_lit q1, mk_aexp_lit q2 =>
                mk_bexp_lit (Qle_bool q2 q1)
            end
      end
  end

with exp_is_equal (e1 e2: Exp) (sigma: state) (n: nat): BexpLit :=
  match n, e1, e2 with
    | O, _, _ => bexp_error
    | S n', EAexp a1, EAexp a2 => aexp_is_equal a1 a2 sigma
    | S n', EBexp b1, EBexp b2 => bexp_is_equal b1 b2 sigma n'
    | S n', ESexp s1, ESexp s2 => sexp_is_equal s1 s2 sigma
    | S n', EUexp u1, EUexp u2 => uexp_is_equal u1 u2
    | S n', EUexp (Uexpid i), EAexp a2 =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_aexp alit) => aexplit_is_equal alit (eval_aexp a2 sigma)
        | _ => mk_bexp_lit false
      end
    | S n', EAexp a2, EUexp (Uexpid i) =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_aexp alit) => aexplit_is_equal alit (eval_aexp a2 sigma)
        | _ => mk_bexp_lit false
      end
    | S n', EUexp (Uexpid i), EBexp b2 =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_bexp blit) => bexplit_is_equal blit (eval_bexp b2 sigma n')
        | _ => mk_bexp_lit false
      end
    | S n', EBexp b2, EUexp (Uexpid i) =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_bexp blit) => bexplit_is_equal blit (eval_bexp b2 sigma n')
        | _ => mk_bexp_lit false
      end
    | S n', EUexp (Uexpid i), ESexp s2 =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_sexp slit) => sexplit_is_equal slit (eval_sexp s2 sigma)
        | _ => mk_bexp_lit false
      end
    | S n', ESexp s2, EUexp (Uexpid i) =>
      match (sigma i) with
        | mk_typ  _ (mk_explit_from_sexp slit) => sexplit_is_equal slit (eval_sexp s2 sigma)
        | _ => mk_bexp_lit false
      end
    | _, _, _ => mk_bexp_lit false (* TODO? This gives false even if one argument evaluates to an error *)
  end

with bexp_is_equal (e1 e2: Bexp) (sigma: state) (n: nat): BexpLit :=
  match n with
    | O => bexp_error
    | S n' => bexplit_is_equal (eval_bexp e1 sigma n') (eval_bexp e2 sigma n')
  end.

Fixpoint eval_exp (e: Exp) (sigma: state) :=
  match e with
    | EAexp a => mk_explit_from_aexp (eval_aexp a sigma)
    | EBexp b => mk_explit_from_bexp (eval_bexp b sigma 5)
    | ESexp s => mk_explit_from_sexp (eval_sexp s sigma)
    | EUexp u => eval_uexp u sigma
  end

with eval_uexp (e: Uexp) (sigma: state) :=
  match e with
    | Uexpid i =>
      match (sigma i) with
        | mk_typ _ t => t
      end
    | Uexpplus e1 e2 =>
      let e1eval := eval_uexp e1 sigma in
      let e2eval := eval_exp e2 sigma in
        match e1eval with
          | mk_explit_from_aexp alit1 =>
            match e2eval with
              | mk_explit_from_aexp alit2 => mk_explit_from_aexp (plus_aexplit alit1 alit2)
              | mk_explit_from_bexp _ => mk_explit_from_bexp bexp_error
              | mk_explit_from_sexp _ => mk_explit_from_sexp sexp_error
              | exp_error => exp_error
            end
          | mk_explit_from_bexp _ => mk_explit_from_bexp bexp_error
          | mk_explit_from_sexp slit1 =>
            match e2eval with
              | mk_explit_from_aexp _ => mk_explit_from_aexp aexp_error
              | mk_explit_from_bexp _ => mk_explit_from_bexp bexp_error
              | mk_explit_from_sexp slit2 => mk_explit_from_sexp (eval_sexp (SConcat (SLit slit1) (SLit slit2)) sigma)
              | exp_error => exp_error
            end
          | exp_error => exp_error
        end
  end.

(** Some tests for bexp eval *)
(* I commented them out because who needs tests anyway - Martin *)
(*Example t1_expr := Or (Lit false) (And (Not (Lit false)) (Lit true)).
Example f1_expr := Or (Lit false) (And (Lit false) (Lit true)).
Example t1_eval: eval_bexp t1_expr = true.
Proof. compute; reflexivity. Qed.
Example f1_eval: eval_bexp f1_expr = false.
Proof. compute; reflexivity. Qed.
*)

(** Inner function for eval_command. It uses a counter n to avoid infinite loops *)
Fixpoint eval_command_inner (cmd: Command) (sigma: state) (n: nat): state :=
  match n with
    | O => sigma (* TODO: Error, infinite loop or large program *)
    | S n' =>
      match cmd with
        | CWhile b c =>
          let blit := eval_bexp b sigma 5 in
          match blit with
            | mk_bexp_lit true =>
              let s' := eval_command_inner c sigma n' in
              eval_command_inner cmd s' n'
            | _ => sigma
          end
        | CRepeat a c =>
          let a' := eval_aexp a sigma in
            match a' with
              | mk_aexp_lit (Qmake 0 1) => sigma
              | mk_aexp_lit (Qmake z 1) =>
                let s' := eval_command_inner c sigma n' in
                  eval_command_inner (CRepeat (ALit (mk_aexp_lit (Qmake (z-1) 1))) c) s' n'
              | _ => sigma (* TODO: Error, repeating on a decimal *)
            end
        | CSet i e => update sigma i (mk_typ false (eval_exp e sigma))
        | CLet i e => update sigma i (mk_typ true (eval_exp e sigma))
        | CSkip => sigma
        | CPrint exp => initial_state (* Trash so the exporter doesnt optimize it out *)
        | CIf b c1 c2 =>
          match eval_bexp b sigma 5 with
            | mk_bexp_lit true => eval_command_inner c1 sigma n'
            | mk_bexp_lit false => eval_command_inner c2 sigma n'
            | bexp_error => sigma (* TODO: Error, if on an error *)
          end
        | CMatch exp Matchbody =>
          match Matchbody with
            | MBNone => sigma
            | MBSome m_exp m_cmd mb =>
              match exp_is_equal exp m_exp sigma 5 with
                | mk_bexp_lit true => eval_command_inner m_cmd sigma n'
                | mk_bexp_lit false => eval_command_inner (CMatch exp mb) sigma n'
                | bexp_error => sigma (* TODO: Error evaluating conditions *)
              end
          end
        | CSeq c1 c2 => eval_command_inner c2 (eval_command_inner c1 sigma n') n'
      end
  end.

Definition eval_command (cmd: Command) (sigma: state): state :=
  eval_command_inner cmd sigma 5.

End Evals.

Export Evals.


Require Import geometry2D.
Require Import Vector.
Require Import fastReals.misc.
Require Import MCInstances.
Require Import fastReals.interface.

Set Implicit Arguments.
Require Import MathClasses.interfaces.vectorspace.

(**Move*)
Lemma inProd0L `{Ring A}: forall (p:Cart2D A), ⟨ 0, p⟩ = 0.
Proof.
  intros ?.
  unfold inprod, InProductCart2D.
  simpl.
  rewrite mult_0_l.
  rewrite mult_0_l.
  rewrite plus_0_l.
  reflexivity.
Qed.

Record ConicSection (A:Type):Type :=
{
  sqrCoeff : (Cart2D A);
  linCoeff : (Cart2D A);
  xyCoeff : A;
  constCoeff : A
}.

(**  The usual instances needed after defining a record type whose
member types may have nonsyntactic equalities: *)

Global Instance EquivConicSection `{Equiv A} :
 Equiv (ConicSection A) := fun a b => (sqrCoeff a = sqrCoeff b)
  /\ (linCoeff a = linCoeff b)
  /\ (xyCoeff a = xyCoeff b)
  /\ (constCoeff a = constCoeff b).

Global Instance EquivalenceCarDim  `{e:Equiv A}
  `{Equivalence _ e}
   : @Equivalence _ (@EquivConicSection _ _).
Proof using.
  unfold equiv, EquivConicSection. split.
  - intros x.
    auto with relations.
  - intros x y. destruct x,y. simpl. intros Hd; repnd;
      split; auto with relations.

  - intros x y z. destruct x,y,z. simpl. intros ? ?.
    repnd.
    split; eauto 3
    with relations.
Qed.

Global Instance ProperquadCoeff `{Equiv A} :
Proper (equiv ==> equiv) (@sqrCoeff A).
Proof.
  intros ? ? Heq. destruct Heq. tauto.
Qed.

Global Instance ProperlinCoeff `{Equiv A}:
Proper (equiv ==> equiv) (@linCoeff A).
Proof.
  intros ? ? Heq. destruct Heq. tauto.
Qed.

Global Instance ProperconstCoeff `{Equiv A} :
Proper (equiv ==> equiv) (@constCoeff A).
Proof.
  intros ? ? Heq. destruct Heq. tauto.
Qed.

Global Instance ProperxyCoeff `{Equiv A} :
Proper (equiv ==> equiv) (@xyCoeff A).
Proof.
  intros ? ? Heq. destruct Heq. tauto.
Qed.

Global Instance ProperxyBuildConic `{Equiv A} :
Proper (equiv ==>equiv ==>equiv ==>equiv ==> equiv) (@Build_ConicSection A).
Proof using.
  intros ? ? H1 ? ? H2 ? ? H3 ? ? H4.
  split; simpl; eauto 3 with typeclass_instances.
Qed.

Section Conic.
(** A is the type of coefficients of the conic section.
We assume that it is an instance of a ring, and has an
[≤] instance which is a [orders.SemiRingOrder].
*)

Set Suggest Proof Using.

Context (A:Type) `{Ring A} `{Le A}
    `{@orders.SemiRingOrder A equiv plus mult zero one le}.

(*Move *)
Definition sqrEach : (Cart2D A) -> (Cart2D A) :=
@castCart A A (fun x => x*x).

Global Instance ProperSqrEach :
Proper (equiv  ==> equiv) (@sqrEach).
Proof using H.
  intros ? ? h1.
  unfold  sqrEach, cast, castCart.
  simpl.
  unfold cast.
  rewrite h1.
  reflexivity.
Qed.

Definition evalConic (c : ConicSection A) (p : Cart2D A) :=
⟨sqrCoeff c, sqrEach p⟩ + ⟨linCoeff c, p⟩
+ (xyCoeff c) * (X p) * (Y p)
+ constCoeff c.

Global Instance ProperEvalConic :
Proper (equiv ==> equiv ==> equiv) evalConic.
Proof using H.
  intros ? ? h1 ? ? h2.
  unfold evalConic, sqrEach.
  unfold cast, castCart, sqrEach.
  simpl.
  unfold cast.
  rewrite h1.
  rewrite h2.
  reflexivity.
Qed.

Require Import MathClasses.interfaces.additional_operations.

(** B^2 - 4*A*C*)
Definition discriminant (c : ConicSection A): A :=
  (xyCoeff c)^2 - 4* (X (sqrCoeff c)) * (Y (sqrCoeff c)).

Definition conicAxisAligned (c : ConicSection A) :=
xyCoeff c = 0.

Definition rotateConicXYTerm  (cs : ConicSection A)  : Cart2D A :=
{| X := xyCoeff cs; Y := Y (sqrCoeff cs) - X (sqrCoeff cs) |}.

Definition rotateConic `{SinClass A} `{CosClass A}
(θ:A) (cs : ConicSection A)  : ConicSection A :=
let a := X (sqrCoeff cs) in
let c := Y (sqrCoeff cs) in
let b := xyCoeff cs in
{|
  sqrCoeff := {|
    X:= a*(cos θ)^2 + b *(sin θ)*(cos θ)  + c*(sin θ)^2;
    Y:= c*(cos θ)^2 - b *(sin θ)*(cos θ)  + a*(sin θ)^2;|};
  linCoeff :=
    {|X:= ⟨linCoeff cs, unitVec θ⟩;
      Y:= ⟨nflip (linCoeff cs), unitVec θ⟩ |};
  xyCoeff := ⟨rotateConicXYTerm cs, unitVec (2*θ)⟩;
  constCoeff := constCoeff cs
|}.

Require Import MathClasses.theory.rings.

Add Ring tempRingA : (stdlib_ring_theory A).

Require Import geometry2DProps.
Require Import geometry2D.

Require Import MCMisc.rings.

Lemma translateNegYConic : ∀ (centre : Cart2D A) (k:A),
let c1:=
{|
  sqrCoeff := negY;
  linCoeff := negY * 2 * centre;
  xyCoeff := 0;
  constCoeff := k
|} in
let c2:=
{|
  sqrCoeff := negY;
  linCoeff := 0;
  xyCoeff := 0;
  constCoeff := k - sqr (X centre) + sqr (Y centre)
|} in
forall p,
evalConic c1 p = evalConic c2 (p+centre).
Proof using.
  intros ? ?.
  simpl. intros ?.
  unfold evalConic.
  simpl.
  rewrite inProd0L.
  unfold inprod, InProductCart2D.
  simpl. unfold normSqr.
  unfold sqr.
  unfold cast.
  ring.
Qed.

End Conic.

Section ConicProps.
Global Instance CastConicSection `{Cast A B}
  : Cast (ConicSection A) (ConicSection B) :=
fun a =>  Build_ConicSection
            ('sqrCoeff a)
            ('linCoeff a)
            ('xyCoeff a)
            ('constCoeff a).

Lemma preserves_RotateConicXYTerm `{c:Cast A B}
 `{@Ring A ae apl am az ao an}
 `{@Ring B be bp bm bz bo bn}
 `{@SemiRing_Morphism A B ae be apl am az ao bp bm bz bo c}
 (cs : ConicSection A)  :
 (rotateConicXYTerm ('cs) : Cart2D B) = ' (rotateConicXYTerm cs) .
Proof.
  simpl. unfold rotateConicXYTerm.
  simpl.
  rewrite <- preserves_minus.
  split; reflexivity.
Qed.

Require Import CartIR2.
Require Import geometry2DProps.
Require Import geometry2D.
Require Import CartIR.
Require Import IRMisc.LegacyIRRing.
Require Import fastReals.interface.

Local Opaque Sin.
Local Opaque Cos.

Lemma rotateConicCorrect : forall (θ:IR)
(cs : ConicSection IR)
(p : Cart2D IR) ,
evalConic (rotateConic θ cs)  p = evalConic cs (rotateAxis (-θ) p).
Proof using.
  intros ? ? ?.
  rewrite rotateAxisInvSimpl.
  unfold rotateConic, evalConic.
  simpl. rewrite unitVDouble.
  do 2 rewrite nat_pow.nat_pow_2.
  simpl.
  unfold rotateAxis, inprod, InProductCart2D.
  simpl.
  unfold cast.
  remember (sin θ) as s.
  remember (cos θ) as c.
  destruct cs.
  destruct sqrCoeff0.
  destruct linCoeff0.
  destruct p.
  simpl.
  rename xyCoeff0 into xy.
  rename constCoeff0 into cc.
  remember (fun x _ :IR => x*x) as sqr.
  (*ring_simplify takes all of the 16GB memory in a few seconds, and never returns.
    The current workaround is to change to a different ring.
    Both on Z, and any abstract MathClasses.abstract_algebra.ring,
    ring_simlify returns within a second.
    On Z, power terms are also reconized in the output.
    Here are the steps.
    1) remember all the non-ring terms. Express constants like 2,3
        inside the ring, e.g. 1+1, 1+1+1
    2) revert all variable to get a closed equality lemma.
    3) Paste it in a new file containing
        Require Import ZArith.
         Open Scope Z_scope.
    4) Replace ℝ by Z in the lemma statement.
        intros and then ring_simplify. Copy the simplified terms here and use
        ring to prove the correctness of the simplification.
        Fortunately, unlike ring_simlify, ring works quickly.
    *)
  match goal with
  [|- ?l = _] => assert
  (l=
X * sqr c 2 * sqr X1 2 - 2 * X * c * s * X1 * Y1 +
X * sqr s 2 * sqr Y1 2 + sqr c 2 * Y * sqr Y1 2 +
c * xy * s * sqr X1 2 - c * xy * s * sqr Y1 2 +
2 * c * s * Y * X1 * Y1 + c * X1 * X0 + c * Y1 * Y0 -
2 * xy * sqr s 2 * X1 * Y1 + xy * X1 * Y1 + sqr s 2 * Y * sqr X1 2 +
s * X1 * Y0 - s * Y1 * X0 + cc )
  as Heq by  (subst sqr; simpl; clear ; IRring)
  end.
  rewrite Heq. clear Heq.

  match goal with
  [|- _ = ?l] => assert
  (l=
X * sqr c 2 * sqr X1 2 - 2 * X * c * s * X1 * Y1 +
X * sqr s 2 * sqr Y1 2 + sqr c 2 * xy * X1 * Y1 +
sqr c 2 * Y * sqr Y1 2 + c * xy * s * sqr X1 2 -
c * xy * s * sqr Y1 2 + 2 * c * s * Y * X1 * Y1 +
c * X1 * X0 + c * Y1 * Y0 - xy * sqr s 2 * X1 * Y1 +
sqr s 2 * Y * sqr X1 2 + s * X1 * Y0 - s * Y1 * X0 + cc )
  as Heq by  (subst sqr; simpl; clear ; IRring)
  end.
  rewrite Heq. clear Heq.
  subst.
  rewrite FFT3.
  IRring.
Qed.

Lemma rotateConicCorrect2 : forall (θ:IR)
(cs : ConicSection IR)
(p : Cart2D IR) ,
evalConic (rotateConic θ cs) (rotateAxis θ p) = evalConic cs p.
Proof using.
  intros.
  remember (rotateAxis θ p) as pp.
  rewrite <- (rotateAxisInvertibleIR p θ).
  subst pp.
  apply rotateConicCorrect.
Qed.

Require Import geometry2D.
Require Import geometry2DProps.

(** The goal is to make it 0, and thus make the conic axis aligned*)
Lemma rotateConicXYCoeff : forall (θ:IR)
(cs : ConicSection Q),
let p : Polar2D IR := ' rotateConicXYTerm cs in
xyCoeff (rotateConic θ ('cs) )=  (rad p) * cos (Vector.θ p - 2 * θ).
Proof using.
  intros.
  hideRight.
  simpl.
  unfold rotateConicXYTerm.
  simpl.
  rewrite <- preserves_minus.
  change
  ({| X := ' xyCoeff cs; Y := ' (Y (sqrCoeff cs) - X (sqrCoeff cs)) |})
  with
  (@cast _ (Cart2D IR) _ (rotateConicXYTerm cs)).
  rewrite CartToPolarCorrect.
  rewrite <- multDotLeft.
  rewrite unitVDot.
  subst.
  reflexivity.
Qed.

End ConicProps.


Require Import Ashley.Axioms.
Require Import Ashley.Set.
Require Import Ashley.Function.
Require Import Ashley.PartialOrder.

(*
injective A -> B implies n(B) >= n(A)
surjective A -> B implies n(A) >= n(B) and n(B) > 0
*)

Instance cardinality_Preorder: Preorder Type:=
{
  within P Q := exists (f : P -> Q), injective f
}.
intros.
exists (fun x => x).
unfold injective.
intros.
exact H.

intros.
destruct H.
destruct H0.
exists (fun p => x (x0 p)).
unfold injective.
unfold injective in H.
unfold injective in H0.
intros.
apply H0.
apply H.
exact H1.
Defined.

Lemma surjective_as_big : forall A B (g : A->B), surjective g -> A >= B.
intros.
unfold within. unfold cardinality_Preorder.
apply sur_right_inverse in H.
destruct H.
destruct H.
exists x.
exact H.
Qed.

Theorem cantor : forall A, A < set A.
unfold within. unfold cardinality_Preorder.
intros.
intro.
destruct H as [f injf].
unfold injective in injf.
set (G := {a : A | exists s, (a = f s /\ ~ s a)}).
destruct (exclude_middle (G (f G))) as [GfG|nGfG].
assert (H := GfG).
unfold G at 1 in H.
destruct H as [s H].
destruct H.
elim H0. clear H0.
cut (G = s).
intro.
rewrite <- H0.
apply GfG.
apply injf.
apply H.
elim nGfG.
unfold G at 1.
exists G.
split.
trivial.
apply nGfG.
Save.


Require Import init.

Require Export relation.

(* begin hide *)
Section OrderDictionary.

Variables U V : Type.

Context `{
    WellOrder U,
    WellOrder V
}.
(* end hide *)
Instance dictionary_order : Order (U * V) := {
    le a b := match a, b with
        | (a1, b1), (a2, b2) => (b1 < b2) ∨ (a1 ≤ a2 ∧ b1 = b2)
        end
}.
(* begin hide *)
Global Instance dict_order_connex : @Connex (U * V) le.
Proof.
    split.
    intros [a1 b1] [a2 b2].
    unfold le; cbn.
    destruct (trichotomy b1 b2) as [[ltq|eq]|ltq].
    -   left; left.
        exact ltq.
    -   destruct (connex a1 a2) as [leq|leq].
        +   left; right.
            split; assumption.
        +   symmetry in eq.
            right; right.
            split; assumption.
    -   right; left.
        exact ltq.
Qed.

Global Instance dict_order_antisym : @Antisymmetric (U * V) le.
Proof.
    split.
    intros [a1 b1] [a2 b2] eq1 eq2.
    unfold le in eq1, eq2; cbn in eq1, eq2.
    destruct eq1 as [ltq1|[leq1 eq1]];
    destruct eq2 as [ltq2|[leq2 eq2]].
    -   destruct (trans ltq1 ltq2); contradiction.
    -   subst.
        destruct ltq1; contradiction.
    -   subst.
        destruct ltq2; contradiction.
    -   pose proof (antisym leq1 leq2).
        subst.
        reflexivity.
Qed.

Global Instance dict_order_trans : @Transitive (U * V) le.
Proof.
    split.
    intros [a1 b1] [a2 b2] [a3 b3] xy yz.
    unfold le in xy, yz; unfold le; cbn in *.
    destruct xy as [ltq1|[leq1 eq1]];
    destruct yz as [ltq2|[leq2 eq2]].
    -   left.
        exact (trans ltq1 ltq2).
    -   subst.
        left.
        exact ltq1.
    -   subst.
        left.
        exact ltq2.
    -   subst.
        right.
        split; [>|reflexivity].
        exact (trans leq1 leq2).
Qed.

Global Instance dict_order_well_founded : @WellOrdered (U * V) le.
Proof.
    split.
    intros S [[a b] Sx].
    pose (SV (b : V) := ∃ a, S (a, b)).
    pose proof (well_ordered SV) as SV_wo.
    prove_parts SV_wo; [>exists b; exists a; exact Sx|].
    destruct SV_wo as [b' [Sb' b'_least]].
    pose (SU (a : U) := S (a, b')).
    pose proof (well_ordered SU Sb') as [a' [Sa' a'_least]].
    exists (a', b').
    split; [>exact Sa'|].
    intros [x y] Sxy.
    unfold le; cbn.
    specialize (b'_least y).
    prove_parts b'_least; [>exists x; exact Sxy|].
    classic_case (b' = y) as [eq|neq].
    -   subst y.
        right.
        split; [>|reflexivity].
        apply a'_least.
        exact Sxy.
    -   left.
        split; assumption.
Qed.

Theorem dict_order_lt : ∀ a b,
    a < b ↔ ((snd a < snd b) ∨ (fst a < fst b ∧ snd a = snd b)).
Proof.
    intros [a1 a2] [b1 b2].
    cbn.
    split.
    -   intros [leq neq].
        destruct leq as [ltq|[leq eq]].
        +   left.
            exact ltq.
        +   subst b2.
            right.
            split; [>|reflexivity].
            split; [>exact leq|].
            intro; subst b1; contradiction.
    -   intros ltq.
        unfold strict.
        unfold le; cbn.
        destruct ltq as [ltq|[ltq eq]].
        +   split.
            *   left.
                exact ltq.
            *   intros contr.
                inversion contr; subst.
                exact (irrefl _ ltq).
        +   subst b2.
            split.
            *   right.
                split; [>|reflexivity].
                apply ltq.
            *   intros contr.
                inversion contr; subst.
                exact (irrefl _ ltq).
Qed.

End OrderDictionary.
(* end hide *)


From Coq Require Import List ZArith Lia.
From Coq Require Zwf.

From CoLoR Require Import weaved_relation equational_theory term_spec terminaison.

Set Implicit Arguments.

Record ordering_pair (A:Type) (eq:A -> A -> Prop)   (lt le : A -> A -> Prop)
:= mk_ordering_pair {
  lt_morph: forall x x', eq x x' -> forall y y', eq y y' -> (lt x y <-> lt x' y');
  lt_irrefl : forall x, ~ lt x x;
  lt_antisym : forall x y, lt x y -> ~lt y x;
  lt_trans : forall x y z, lt x y -> lt y z -> lt x z;
  le_morph : forall x x', eq x x' -> forall y y', eq y y' -> (le x y <-> le x' y');
  le_refl : forall x, le x x;
  le_antisym : forall x y, le x y -> le y x -> eq x y;
  le_trans : forall x y z, le x y -> le y z -> le x z;
  le_lt_compat_left : forall x y z, le x y -> lt y z -> lt x z;
  le_lt_compat_right : forall x y z, lt x y -> le y z -> lt x z;
  lt_included_le : forall x y, lt x y -> le x y
}.

Definition o_Z : forall m, ordering_pair (@eq Z) (Zwf.Zwf m) Z.le.
Proof.
  intros m.
  constructor.
  intros;subst;reflexivity.
  intros x;intro abs;destruct abs;lia.
  intros x y H;destruct H;intro abs;destruct abs;lia.
  intros x y z H1 H2;destruct H1; destruct H2;constructor;lia.
  intros;subst;reflexivity.
  intros x;lia.
  intros x y  H1 H2;lia.
  intros x y z H1 H2;lia.
  intros x y z H1 H2;destruct H2;split;lia.
  intros x y z H1 H2;destruct H1;split;lia.
  intros x y H1;destruct H1;lia.
Defined.

Module Interp(EQT:equational_theory_spec.EqTh).
  Import EQT.
  Import T.
  Import F.

 Section S.
   Hypothesis A : Type.

   Hypothesis Ale Alt Aeq : A -> A -> Prop.

   Hypothesis Aop : ordering_pair Aeq Alt Ale.

   Hypothesis A0 : A.
   Fixpoint Pol_type (n:nat) :=
     match n with
       | 0 => A
       | S n => A -> Pol_type n
     end.

   Definition get_arity f :=
     match arity f with
       | term_spec.Free n => n
       | _ => 2
     end.

   Fixpoint Pol_null (n:nat) : Pol_type n :=
     match n with
       | 0 => A0
       | S n => (fun _ : A => Pol_null n)
     end.

   Hypothesis Pols : forall f, Pol_type (get_arity f).

   Definition measure : term -> A.
   Proof.
     fix measure 1.
     intros [a | f l].
     exact A0.
     assert (f_pol := Pols f).
     clear Pols.
     set (n:= get_arity f) in *.
     clearbody n.
     revert l n f_pol.
     fix measure_list 1.
     intros [| t l].
     intros [| n].
     intros a;exact a.
     intros _;exact A0.
     intros [| n].
     intros _;exact A0.
     simpl.
     intros.
     apply measure_list with (n:=n).
     apply l.
     apply f_pol.
     apply (measure t).
   Defined.

   Fixpoint measure_list (l: list term) : forall n0 : nat, Pol_type n0 -> A :=
     match l with
       | nil =>
         fun n0 : nat =>
           match n0 as n1 return (Pol_type n1 -> A) with
             | 0 => fun a : Pol_type 0 => a
             | S n1 => fun _ : Pol_type (S n1) => A0
           end
       | t0 :: l1 =>
         fun n0 : nat =>
           match n0 as n1 return (Pol_type n1 -> A) with
             | 0 => fun _ : Pol_type 0 => A0
             | S n1 =>
               fun f_pol0 : A -> Pol_type n1 =>
                 measure_list l1 n1 (f_pol0 (measure t0))
           end
     end.

   Local Notation "a <= b" := (Ale a b).
   Local Notation "a < b" := (Alt a b).

   Fixpoint monotonic_aux n : Pol_type n -> Pol_type n -> Prop:=
     match n as m return Pol_type m -> Pol_type m -> Prop with
       | 0 => fun a b => Ale a b
       | S n => fun P1 P2 =>
         forall x1 x2, (A0<=x1) /\ (x1 <= x2) -> monotonic_aux n (P1 x1) (P2 x2)
     end.

   Definition monotonic f (Pols:Pol_type (get_arity f)) :=
     monotonic_aux (get_arity f) Pols Pols.
   Hypothesis All_monotonic : forall f, monotonic f (Pols f).

   Fixpoint bounded_aux n : Pol_type n -> Type:=
     match n as m return Pol_type m -> Type with
       | 0 => fun a => Ale A0 a
       | S n => fun P1 =>
         forall x1, (A0<=x1) -> bounded_aux n (P1 x1)
     end.

   Definition bounded f (Pols : forall f, Pol_type (get_arity f))
     := bounded_aux (get_arity f) (Pols f).
   Hypothesis All_bounded : forall f, bounded f Pols.

   Lemma measure_bounded : forall t, A0 <= measure t.
   Proof.
     fix measure_bounded 1.
     intros [a | f l].
     simpl.
     apply Aop.(le_refl).
     unfold measure.
     generalize (All_bounded f).
     unfold bounded.
     set (f_pol := Pols f).
     clearbody f_pol.
     revert f_pol.
     generalize (get_arity f).
     revert l .
     fix measure_bounded_list 1.
     intros [|t l].
     intros [|n].
     intros a.
     simpl. intros p;exact p.
     intros _ _;apply Aop.(le_refl).
     intros [|n] f_pol Hb.
     apply Aop.(le_refl).
     simpl in f_pol,Hb|-.
     apply measure_bounded_list.
     apply Hb.
     apply measure_bounded.
   Qed.

   Hypothesis rules : term -> term -> Prop.
   Hypothesis rules_monotonic :
    forall l r,
     (EQT.axiom rules r l) -> measure r <= measure l.

Lemma measure_monotonic_aux :
  forall l
    (IHl : forall t : term, In t l ->
           forall r : term, one_step rules r t -> measure r <= measure t)
      k1, one_step_list (one_step rules) k1 l ->
  forall n (P1 P2 : Pol_type n), monotonic_aux n P1 P2 ->
           measure_list k1 n P1 <= measure_list l n P2.
Proof.
intros l IHl k1 H1.
destruct (one_step_in_list H1) as [t1 [t2 [l1 [l2 [K [K1 K2]]]]]].
assert (Ht : measure t2 <= measure t1).
apply IHl; [subst; apply in_or_app; right; left; apply eq_refl | assumption].
subst l k1.
clear IHl H1 K.
induction l1 as [ | a1 l1]; intros [ | n] P1 P2 Hmon; simpl.
apply Aop.(le_refl).
simpl in P1, P2, Hmon.
set (P1':=P1 (measure t2)).
set (P2':=P2 (measure t1)).
assert (Hmon':monotonic_aux n P1' P2').
unfold P1', P2'.
apply Hmon with (x1:=measure t2) (x2:=measure t1).
split; [apply measure_bounded | assumption].
clearbody P1';clearbody P2'.
clear P1 P2 Hmon.
revert n P1' P2' Hmon'.
induction l2 as [|t l];intros n P1 P2 Hmon.
simpl.
destruct n.
simpl in *.
apply Hmon.
apply Aop.(le_refl).
simpl.
destruct n.
apply Aop.(le_refl).
apply IHl.
apply Hmon.
split;[apply measure_bounded| apply Aop.(le_refl)].
apply Aop.(le_refl).

apply IHl1; trivial.
simpl in P1, P2, Hmon.
apply Hmon.
split;[apply measure_bounded| apply Aop.(le_refl)].
Qed.

Lemma measure_monotonic :
    forall l r,
     (EQT.one_step rules r l) -> measure r <= measure l.
   Proof.
   intro l; pattern l; apply term_rec3; clear l.
   (* 1/2 variable case *)
   intros v r H; inversion H as [t1 t2 H1 | ]; clear H; subst.
   apply rules_monotonic; assumption.
   (* 1/2 compound term case *)
   intros f l IHl r H.
   inversion H as [t1 t2 H1 | g k1 k2 H1 H2 H3];
   clear H; subst.
   apply rules_monotonic; assumption.
   assert (IH : forall n (P1 P2 : Pol_type n), monotonic_aux n P1 P2 ->
           measure_list k1 n P1 <= measure_list l n P2).
   apply measure_monotonic_aux; trivial.
   simpl; apply IH; apply All_monotonic.
   Qed.

   Lemma measure_list_monotonic :
    forall l1 l2,
     (one_step_list (one_step rules) l1 l2) ->
     forall n (P1 P2:Pol_type n), monotonic_aux  n P1 P2 ->
       measure_list l1 n P1 <= measure_list l2 n P2.
   Proof.
     intros l1 l2 H.
     apply measure_monotonic_aux; trivial.
     intros t t_in_l2; apply measure_monotonic.
   Qed.

      Lemma measure_star_monotonic :
    forall l r,
     (refl_trans_clos (EQT.one_step rules) r l) ->
      measure r <= measure l.
   Proof.
     intros.
     destruct H as [x | r l H].
     apply Aop.(le_refl).
     induction H.
     apply measure_monotonic; assumption.
     apply Aop.(le_trans) with (measure y).
     apply measure_monotonic; assumption.
     assumption.
   Qed.

   Hypothesis Marked_pols : forall f, (defined rules f) -> Pol_type (get_arity f).
   Hypothesis defined_dec : forall f, {defined rules f} + {~defined rules f}.
   Hypothesis Marked_pols_monononic : forall f (H:defined rules f), monotonic f (Marked_pols H).

   Definition marked_measure : term -> A.
   Proof.
     fix marked_measure 1.
     intros [a|f l].
     exact (measure (Var a)).
     case (defined_dec f).
     intros Hdef.
     apply (measure_list l (get_arity f) (Marked_pols Hdef)).
     intros _ ;apply (measure (Term f l)).
   Defined.

   Lemma marked_measure_monotonic :
    forall f l1 l2,
     (one_step_list (one_step rules) l2 l1) ->
     marked_measure (Term f l2) <= marked_measure (Term f l1).
   Proof.
     intros f l1 l2 H.
     simpl.
     case (defined_dec f);[intro Hdef|intro Hconst].
     apply measure_list_monotonic. assumption.
     apply Marked_pols_monononic.

     apply measure_list_monotonic. assumption.
     apply All_monotonic.
   Qed.

   Lemma marked_measure_star_monotonic :
    forall f l1 l2,
      refl_trans_clos (one_step_list (one_step rules)) l2 l1 ->
     marked_measure (Term f l2) <= marked_measure (Term f l1).
   Proof.
     intros .
     destruct H as [x | r l H].
     apply Aop.(le_refl).
     induction H.
     apply marked_measure_monotonic; assumption.
     apply Aop.(le_trans) with (marked_measure (Term f y)).
     apply marked_measure_monotonic; assumption.
     assumption.
   Qed.

   Hypothesis rules_ref :
     forall s t : term,
       rules s t -> forall x : variable, In x (var_list s) -> In x (var_list t).

   Hypothesis  rules_non_var: forall (v : variable) (t : term), ~ rules t (Var v) .

   Hypothesis rules_well_formed :
     forall s t : term, rules s t -> well_formed s /\ well_formed t.

   Hypothesis inject : nat -> variable.
   Hypothesis inject_inv : variable -> nat.

   Hypothesis inject_inverse : forall n : nat, inject_inv (inject n) = n.

   Hypothesis rules_strictly_monotonic :
     forall l r,
       (EQT.axiom rules r l) ->
       well_formed l -> measure r < measure l.

   Fixpoint monotonic_strict_aux b n : Pol_type n -> Pol_type n -> Prop:=
     match n as m return Pol_type m -> Pol_type m -> Prop with
       | 0 => fun a b => Alt a b
       | S n =>
         match b with
           | true =>
             fun P1 P2 =>
               forall x1 x2, (A0<=x1) /\ (x1 <= x2) -> monotonic_strict_aux true n (P1 x1) (P2 x2)
           | false =>
             fun P1 P2 =>
               (forall x1 x2, (A0<=x1) /\ (x1 <= x2) -> monotonic_strict_aux false n (P1 x1) (P2 x2))/\
               (forall x1 x2, (A0<=x1) /\ (x1 < x2) -> monotonic_strict_aux true n (P1 x1) (P2 x2))
         end
     end.

   Hypothesis All_strictly_monotonic : forall f,
     match get_arity f with
       | 0 => True
       | _ => monotonic_strict_aux false (get_arity f) (Pols f) (Pols f)
     end.

Lemma measure_strictly_monotonic_aux :
  forall l2  (IHl2 : forall t : term, In t l2 ->
           forall r : term, one_step rules r t -> well_formed t -> measure r < measure t),
  forall l1, one_step_list (one_step rules) l1 l2 -> (forall t, In t l2 -> well_formed t) ->
  forall n (P1 P2 : Pol_type n), length l2 = n -> monotonic_strict_aux false n P1 P2 ->
  measure_list l1 n P1 < measure_list l2 n P2.
Proof.
intros l IHl k1 H1 Wl.
destruct (one_step_in_list H1) as [t1 [t2 [l1 [l2 [K [K1 K2]]]]]].
assert (Ht : measure t2 < measure t1).
apply IHl; [idtac | assumption | apply Wl]; subst; apply in_or_app; right; left; apply eq_refl.
subst l k1.
clear IHl H1 K Wl.
induction l1 as [ | a1 l1]; intros [ | n] P1 P2 L Hmon; simpl.
discriminate.
simpl in P1, P2, Hmon, L; injection L; clear L; intro L.
set (P1':=P1 (measure t2)).
set (P2':=P2 (measure t1)).
assert (Hmon' : monotonic_strict_aux true n P1' P2').
unfold P1', P2'.
destruct Hmon as [_ Hmon].
apply Hmon with (x1:=measure t2) (x2:=measure t1).
split; [apply measure_bounded | assumption].
clearbody P1'; clearbody P2'.
clear P1 P2 Hmon.
revert n P1' P2' Hmon' L.
induction l2 as [ | t l]; intros n P1 P2 Hmon L.
simpl in *; subst n; apply Hmon.
destruct n.
discriminate L.
simpl in *; apply IHl.
apply Hmon; split;[apply measure_bounded| apply Aop.(le_refl)].
injection L; intro; assumption.
discriminate L.
apply IHl1.
injection L; intro; assumption.
apply Hmon; split;[apply measure_bounded| apply Aop.(le_refl)].
Qed.

   Lemma measure_strictly_monotonic :
    forall l r, (EQT.one_step rules r l) -> well_formed l -> measure r < measure l.
   Proof.
   Proof.
   intro l; pattern l; apply term_rec3; clear l.
   (* 1/2 variable case *)
   intros v r H; inversion H as [t1 t2 H1 | ]; clear H; subst.
   apply rules_strictly_monotonic; assumption.
   (* 1/2 compound term case *)
   intros f l IHl r H W.
   inversion H as [t1 t2 H1 | g k1 k2 H1 H2 H3];
   clear H; subst.
   apply rules_strictly_monotonic; assumption.
   assert (L : length l = get_arity f).
   unfold well_formed in W; simpl in W; rewrite Bool.andb_true_iff in W; destruct W as [_ W].
   apply beq_nat_true; unfold get_arity; destruct (arity f) as [ | | n]; assumption.
   apply measure_strictly_monotonic_aux; trivial.
   apply (well_formed_unfold W).
   generalize (All_strictly_monotonic f);
   set (f_pol:=Pols f).
   clearbody f_pol.
   revert f_pol.
   rewrite <- L.
   revert H1; case l; [intro H1; inversion H1 | intros a1 l1  _; intros; assumption].
   Qed.

   Lemma measure_list_strictly_monotonic :
     forall l1 l2 (H : one_step_list (one_step rules) l1 l2),
       (forall t, In t l2 -> well_formed t) ->
       forall n (P1 P2:Pol_type n), length l2 =  n -> monotonic_strict_aux false n P1 P2 ->
         measure_list l1 n P1 < measure_list l2 n P2.
   Proof.
     intros l1 l2 H Wl2.
     apply measure_strictly_monotonic_aux; [idtac | assumption | assumption].
     intros; apply measure_strictly_monotonic; assumption.
   Qed.

 End S.

End Interp.