(** * MoreCoq: More About Coq's Tactics *)

Require Export Poly.

(** This chapter introduces several more proof strategies and
    tactics that, together, allow us to prove theorems about the
    functional programs we have been writing. In particular, we'll
    reason about functions that work with natural numbers and lists.

    In particular, we will see:
    - how to use auxiliary lemmas, in both forwards and backwards reasoning;
    - how to reason about data constructors, which are injective and disjoint;
    - how to create a strong induction hypotheses (and when
      strengthening is required); and
    - how to reason by case analysis.
 *)

(* ###################################################### *)
(** * 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 o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.
  (* At this point, we could finish with
     "[rewrite -> eq2. reflexivity.]" as we have
     done several times above. But we can achieve the
     same effect in a single step by using the
     [apply] tactic instead: *)
  apply eq2.  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  ->
     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] binding some _universal 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, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  intros thm fact.
  apply thm.
  apply fact.
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_firsttry : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  simpl.
  (* Here we cannot use [apply] directly *)
Abort.

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

Theorem silly3 : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  symmetry.
  simpl. (* Actually, this [simpl] is unnecessary, since
            [apply] will perform simplification first. *)
  apply H.  Qed.

(** **** Exercise: 3 stars (apply_exercise1)  *)
(** Hint: you can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [SearchAbout] is
    your friend. *)

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, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  Are there 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
    abstract it out as a lemma recording 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, we usually don't have to include the name [m]
    in the [with] clause; Coq is often smart enough to
    figure out which instantiation we're giving. We could
    instead write: [apply trans_eq with [c,d]]. *)

(** **** Exercise: 3 stars, optional (apply_with_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 eq1 eq2.
  apply trans_eq with (m).
  apply eq2.
  apply eq1.
Qed.
(** [] *)

(* ###################################################### *)
(** * The [inversion] tactic *)

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is clear 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 (and in our informal
    understanding of how datatype declarations work in other
    programming languages) are two other facts:

    - The constructor [S] is _injective_.  That is, the only way we can
      have [S n = S m] is if [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 all inductively defined types: 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 unequal.  (Since neither [true]
    nor [false] take any arguments, their injectivity is not an issue.) *)

(** Coq provides a tactic called [inversion] that allows us to exploit
    these principles in proofs.

    The [inversion] tactic is used like this.  Suppose [H] is a
    hypothesis in the context (or a previously proven lemma) of the
    form
      c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] instructs Coq to "invert" this
    equality to extract the information it contains about these terms:

    - If [c] and [d] are the same constructor, then we know, by the
      injectivity of this constructor, that [a1 = b1], [a2 = b2],
      etc.; [inversion H] adds these facts to the context, and tries
      to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory.  That is, a false assumption has crept
      into the context, and this means that any goal whatsoever is
      provable!  In this case, [inversion H] marks the current goal as
      completed and pops it off the goal stack. *)

(** The [inversion] tactic is probably easier to understand by
    seeing it in action than from general descriptions like the above.
    Below you will find example theorems that demonstrate the use of
    [inversion] and exercises to test your understanding. *)

Theorem eq_add_S : forall (n m : nat),
     S n = S m ->
     n = m.
Proof.
  intros n m eq. inversion eq. reflexivity.  Qed.

Theorem silly4 : forall (n m : nat),
     [n] = [m] ->
     n = m.
Proof.
  intros n o eq. inversion eq. reflexivity.  Qed.

(** As a convenience, the [inversion] tactic can also
    destruct equalities between complex values, binding
    multiple variables as it goes. *)

Theorem silly5 : forall (n m o : nat),
     [n;m] = [o;o] ->
     [n] = [m].
Proof.
  intros n m o eq. inversion eq. reflexivity. Qed.

(** **** Exercise: 1 star (sillyex1)  *)
Example sillyex1 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = z :: j ->
     y :: l = x :: j ->
     x = y.
Proof.
  intros X x y z l j eq1 eq2.
  inversion eq2.
  reflexivity.
Qed.
(** [] *)

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

Theorem silly7 : forall (n m : nat),
     false = true ->
     [n] = [m].
Proof.
  intros n m contra. inversion contra.  Qed.

(** **** Exercise: 1 star (sillyex2)  *)
Example sillyex2 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = [] ->
     y :: l = z :: j ->
     x = z.
Proof.
  intros X x y z l j eq1.
  inversion eq1.
Qed.
(** [] *)

(** While the injectivity of constructors allows us to reason
    [forall (n m : nat), S n = S m -> n = m], the reverse direction of
    the implication is an instance of a more general fact about
    constructors and functions, which we will often find useful: *)

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.

(** **** Exercise: 2 stars, optional (practice)  *)
(** A couple more nontrivial but not-too-complicated proofs to work
    together in class, or for you to work as exercises. *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  intros n H.
  destruct n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    inversion H.
Qed.

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  intros n H.
  destruct n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    inversion 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 in
    the hypothesis named [H] in the context. *)

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

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

    In other words, [apply L in H] gives us a form of "forward
    reasoning" -- from [L1 -> L2] and a hypothesis matching [L1], it
    gives us a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning" -- it says that if we know [L1->L2] and we
    are trying to prove [L2], it suffices to prove [L1].

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

Theorem silly3' : forall (n : nat),
  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
     true = beq_nat n 5  ->
     true = beq_nat (S (S n)) 7.
Proof.
  intros n 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.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, Coq tends to favor backward reasoning, but in some
    situations the forward style can be easier to use or to think
    about.  *)

(** **** Exercise: 3 stars (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise. *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      inversion H.
  Case "n = S n'".
    intros m.
    destruct m as [| m'].
    SCase "m = 0".
      intros H.
      inversion H.
    SCase "m = S m'".
      intros H.
      rewrite <- plus_n_Sm in H.
      rewrite <- plus_n_Sm in H.
      inversion H.
      apply f_equal.
      apply IHn'.
      apply H1.
Qed.
(** [] *)

(* ###################################################### *)
(** * 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 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 the [double] function is injective -- i.e.,
    that it always 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 little bit delicate: if we
    begin it with
      intros n. induction n.
]]
    all is well.  But if we begin it with
      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'].
  Case "n = O". simpl. intros eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'". intros eq. destruct m as [| m'].
    SCase "m = O". inversion eq.
    SCase "m = S m'".  apply f_equal.
      (* Here we are stuck.  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 _this 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 that
    the proposition

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

    holds for all [n] by showing

      - [P O]

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

      - [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: it says 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 [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 with proving [R]!  (If we
    tried to prove [R] from [Q], we would say something like "Suppose
    [double (S n) = 10]..." but then we'd be stuck: knowing that
    [double (S n)] is [10] tells us nothing about whether [double n]
    is [10], so [Q] is useless at this point.) *)

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

(** The good proof of [double_injective] leaves [m] 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'].
  Case "n = O". simpl. intros m eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'".
    (* Notice that both the goal and the induction
       hypothesis have changed: the goal asks us to prove
       something more general (i.e., to 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 choose a particular [m] and introduce the
       assumption that [double n = double m].  Since we
       are doing a case analysis on [n], we need a case
       analysis on [m] to keep the two "in sync." *)
    destruct m as [| m'].
    SCase "m = O".
      (* The 0 case is trivial *)
      inversion eq.
    SCase "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 at this point is actually the
         predecessor of the one 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
         [m'] that we are talking about right now (this
         instantiation is performed automatically by
         [apply]), then [IHn'] gives us exactly what we
         need to finish the proof. *)
      apply IHn'. inversion eq. reflexivity. Qed.

(** What this teaches us is that we need to be careful about using
    induction to try to prove something too specific: If we're proving
    a property of [n] and [m] by induction on [n], we may need to
    leave [m] generic. *)

(** The proof of this theorem (left as an exercise) has to be treated similarly: *)

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  induction n as [| n'].
  Case "n = 0".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      inversion H.
  Case "n = S n'".
    intros m H.
    destruct m as [| m'].
    SCase "m = 0".
      inversion H.
    SCase "m = S m'".
      apply IHn' in H.
      rewrite -> H.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)

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

(** The strategy of doing fewer [intros] before an [induction] doesn't
    always work directly; sometimes a little _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'].
  Case "m = O". simpl. intros eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "n = S n'".  apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (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
    will work, but it's not nice: We don't want to have to mangle the
    statements of lemmas to fit the needs of a particular strategy for
    proving them -- we want to state them in the most clear and
    natural way. *)

(**  What we can do instead is to first introduce all the
    quantified variables and then _re-generalize_ one or more of
    them, taking them 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'].
  Case "m = O". simpl. intros n eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros n eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "n = S n'". apply f_equal.
      apply IHm'. inversion eq. reflexivity. 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 this is what we wanted to show.  Otherwise, if [n = S
    n'] for some [n'], we derive a contradiction: by the definition of
    [double] we would have [double n = S (S (double n'))], but this
    contradicts the assumption that [double n = 0].

  - Otherwise, 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 inversion 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. [] *)

(** Here's another illustration of [inversion] and using an
    appropriately general induction hypothesis.  This is a slightly
    roundabout way of stating a fact that we have already proved
    above.  The extra equalities force us to do a little more
    equational reasoning and exercise some of the tactics we've seen
    recently. *)

Theorem length_snoc' : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l. induction l as [| v' l'].

  Case "l = []".
    intros n eq. rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    intros n eq. simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.

(** It might be tempting to start proving the above theorem
    by introducing [n] and [eq] at the outset.  However, this leads
    to an induction hypothesis that is not strong enough.  Compare
    the above to the following (aborted) attempt: *)

Theorem length_snoc_bad : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l n eq. induction l as [| v' l'].

  Case "l = []".
    rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)

(** As in the double examples, the problem is that by
    introducing [n] before doing induction on [l], the induction
    hypothesis is specialized to one particular natural number, namely
    [n].  In the induction case, however, we need to be able to use
    the induction hypothesis on some other natural number [n'].
    Retaining the more general form of the induction hypothesis thus
    gives us more flexibility.

    In general, a good rule of thumb is to make the induction hypothesis
    as general as possible. *)

(** **** Exercise: 3 stars (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem index_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     index n l = None.
Proof.
  intros n X l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros n H.
    reflexivity.
  Case "l = h :: t".
    intros n H.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      inversion H.
      apply IHt.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)
(** Write an informal proof corresponding to your Coq proof
    of [index_after_last]:

     _Theorem_: For all sets [X], lists [l : list X], and numbers
      [n], if [length l = n] then [index n l = None].

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

(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)
(** Prove this by induction on [l]. *)

Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : list X),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros n X v l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros n H.
    simpl in H.
    rewrite <- H.
    reflexivity.
  Case "l = h :: t".
    intros n H.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      apply IHt.
      inversion H.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (app_length_cons)  *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  intros X l1.
  induction l1 as [| h t].
  Case "l1 = []".
    intros.
    rewrite <- H.
    reflexivity.
  Case "l1 = h :: t".
    intros.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      apply IHt with (x).
      inversion H.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 4 stars, optional (app_length_twice)  *)
(** Prove this by induction on [l], without using app_length. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  assert (forall (X : Type) (l1 l2 : list X) (x : X) (n : nat),
    length (l1 ++ l2) = n -> length (l1 ++ (x :: l2)) = S n
  ) as app_length_cons'.
  Case "Proof of assertion".
    intros X l1.
    induction l1 as [| h t].
    SCase "l = nil".
      intros.
      rewrite <- H.
      reflexivity.
    SCase "l = h :: t".
      intros.
      destruct n as [| n'].
      SSCase "n = 0".
        inversion H.
      SSCase "n = S n'".
        simpl.
        apply f_equal.
        apply IHt.
        inversion H.
        reflexivity.
  intros X n l.
  generalize dependent n.
  induction l as [| h t].
  Case "l = []".
    intros.
    rewrite <- H.
    reflexivity.
  Case "l = h :: t".
    intros.
    destruct n as [| n'].
    SCase "n = 0".
      inversion H.
    SCase "n = S n'".
      simpl.
      apply f_equal.
      rewrite <- plus_n_Sm.
      apply app_length_cons'.
      apply IHt.
      inversion H.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (double_induction)  *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  intros P H.
  induction m as [| m'].
  Case "m = 0".
    induction n as [| n'].
    SCase "n = 0".
      apply H.
    SCase "n = S n'".
      apply H1.
      apply IHn'.
  Case "m = S m'".
    induction n as [| n'].
    SCase "n = 0".
      apply H0.
      apply IHm'.
    SCase "n = S n'".
      apply H2.
      apply IHm'.
Qed.
(** [] *)

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

(** We have seen many examples where the [destruct] tactic is
    used to perform case analysis of the value of some variable.  But
    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 beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (beq_nat n 3).
    Case "beq_nat n 3 = true". reflexivity.
    Case "beq_nat n 3 = false". destruct (beq_nat n 5).
      SCase "beq_nat n 5 = true". reflexivity.
      SCase "beq_nat n 5 = false". reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,
    either [n] is equal to [3] or it isn't, so we use [destruct
    (beq_nat 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: 1 star (override_shadow)  *)
Theorem override_shadow : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  (override (override f k1 x2) k1 x1) k2 = (override f k1 x1) k2.
Proof.
  intros.
  unfold override.
  destruct (beq_nat k1 k2).
  Case "beq_nat k1 k2 = true".
    reflexivity.
  Case "beq_nat k1 k2 = false".
    reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
(** Complete the proof below *)

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 [| (x, y) t].
  Case "l = []".
    intros l1 l2 H.
    inversion H.
    reflexivity.
  Case "l = (x, y) :: t".
    intros l1 l2 H.
    simpl in H.
    destruct (split t) as [xs ys].
    destruct l1 as [| h1 t1].
    SCase "l1 = []".
      inversion H.
    SCase "l1 = h1 :: t1".
      destruct l2 as [| h2 t2].
      SSCase "l2 = []".
        inversion H.
      SSCase "l2 = h2 :: t2".
        assert ((xs, ys) = (t1, t2)).
        SSSCase "Proof of assertion".
          inversion H.
          reflexivity.
        apply IHt in H0.
        rewrite <- H0.
        simpl.
        inversion H.
        reflexivity.
Qed.
(** [] *)

(** Sometimes, doing a [destruct] on a compound expression (a
    non-variable) will erase information we need to complete a proof. *)
(** For example, suppose
    we define a function [sillyfun1] like this: *)

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

(** And suppose that we want to convince Coq of the rather
    obvious observation that [sillyfun1 n] yields [true] only when [n]
    is odd.  By analogy with the proofs we did with [sillyfun] above,
    it is natural to start the proof like this: *)

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

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution peformed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat 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, in this branch of the case
    analysis, [beq_nat n 3 = true], it must be that [n = 3], from
    which it follows that [n] is odd.

    What we would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation (with whatever
    name we choose). *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat 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. *)
    Case "e3 = true". apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    Case "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, allow us to finish the proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        SCase "e5 = true".
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        SCase "e5 = false". inversion eq.  Qed.

(** **** Exercise: 2 stars (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f.
  destruct b.
  Case "b = true".
    destruct (f true) eqn:Htrue.
    SCase "f true = true".
      rewrite -> Htrue.
      apply Htrue.
    SCase "f true = false".
      destruct (f false) eqn:Hfalse.
      SSCase "f false = true".
        apply Htrue.
      SSCase "f false = false".
        apply Hfalse.
  Case "b = false".
      destruct (f false) eqn:Hfalse.
      SCase "f false = true".
        destruct (f true) eqn:Htrue.
        SSCase "f true = true".
          apply Htrue.
        SSCase "f true = false".
          apply Hfalse.
      SCase "f false = false".
        rewrite -> Hfalse.
        apply Hfalse.
Qed.

(** **** Exercise: 2 stars (override_same)  *)
Theorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),
  f k1 = x1 ->
  (override f k1 x1) k2 = f k2.
Proof.
  intros X x1 k1 k2 f H.
  unfold override.
  destruct (beq_nat k1 k2) eqn:Heq.
  Case "beq_nat k1 k2 = true".
   apply beq_nat_true in Heq.
   rewrite <- Heq.
   symmetry.
   apply H.
  Case "beq_nat k1 k2 = false".
    reflexivity.
Qed.
(** [] *)

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

(** We've now seen a bunch of Coq's fundamental tactics.  We'll
    introduce a few more as we go along through the coming lectures,
    and later in the course we'll introduce some more powerful
    _automation_ tactics that make Coq do more of the low-level work
    in many cases.  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]

      - [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

      - [inversion]:
        reason by injectivity and distinctness of constructors

      - [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
*)

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

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  induction n as [| n'].
  Case "n = 0".
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      reflexivity.
  Case "n = S n'".
    destruct m as [| m'].
    SCase "m = 0".
      reflexivity.
    SCase "m = S m'".
      simpl.
      apply IHn'.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

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

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  intros n m p eqnm eqmp.
  apply beq_nat_true in eqnm.
  apply beq_nat_true in eqmp.
  rewrite -> eqnm.
  rewrite <- eqmp.
  symmetry.
  apply beq_nat_refl.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We have just proven 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?)  *)

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

Theorem split_combine : split_combine_statement.
Proof.
  intros X Y.
  induction l1 as [| h1 t1].
  Case "l1 = []".
    destruct l2 as [| h2 t2].
    SCase "l2 = []".
      intros H.
      reflexivity.
    SCase "l2 = h2 :: t2".
      intros contra.
      inversion contra.
  Case "l1 = h1 :: t1".
    destruct l2 as [| h2 t2].
    SCase "l2 = []".
      intros contra.
      inversion contra.
    SCase "l2 = h2 :: t2".
      intros H.
      simpl in H.
      inversion H.
      apply IHt1 in H1.
      simpl.
      rewrite -> H1.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars (override_permute)  *)
Theorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  intros.
  unfold override.
  destruct (beq_nat k1 k3) eqn:eq13.
  Case "beq_nat k1 k3 = true".
    destruct (beq_nat k2 k3) eqn:eq12.
    SCase "beq_nat k2 k3 = true".
      apply beq_nat_true in eq13.
      apply beq_nat_true in eq12.
      rewrite -> eq12 in H.
      rewrite -> eq13 in H.
      rewrite <- beq_nat_refl in H.
      inversion H.
    SCase "beq_nat k2 k3 = false".
      reflexivity.
  Case "beq_nat k1 k3 = false".
    destruct (beq_nat k2 k3) eqn:eq12.
    SCase "beq_nat k2 k3 = true".
      reflexivity.
    SCase "beq_nat k2 k3 = false".
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your IH. *)

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.
  induction l as [| h t].
  Case "l = []".
    intros lf contra.
    inversion contra.
  Case "l = h :: t".
    intros lf H.
    simpl in H.
    destruct (test h) eqn:Htest.
    SCase "test h = true".
      inversion H.
      rewrite <- H1.
      apply Htest.
    SCase "test h = false".
      apply IHt with (lf).
      apply H.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:
      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (beq_nat 5) [] = true
    The second checks whether there exists an element in the list that
    satisfies a given predicate:
      existsb (beq_nat 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

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

    Prove theorem [existsb_existsb'] 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.

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.

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

Theorem existsb_existsb' :
  forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof.
  intros X test.
  induction l as [| h t].
  Case "l = []".
    reflexivity.
  Case "l = h :: t".
    simpl.
    destruct (test h) eqn:H.
    SCase "test h = true".
      unfold existsb'.
      simpl.
      rewrite -> H.
      reflexivity.
    SCase "test h = false".
      unfold existsb'.
      simpl.
      rewrite -> H.
      rewrite -> IHt.
      reflexivity.
Qed.
(** [] *)

(** $Date: 2014-12-31 16:01:37 -0500 (Wed, 31 Dec 2014) $ *)


(* A depth-first search algorithm. *)

Require Import PeanoNat.
From larith Require Import A_setup B1_utils.

Section Stateful_search.

Variable X state solution : Type.
Variable check : state -> X -> state + solution.

Fixpoint search s l : state + (X × solution) :=
  match l with
  | []      => inl s
  | x :: l' =>
    match check s x with
    | inl t => search t l'
    | inr y => inr (x, y)
    end
  end.

Theorem search_app s l1 l2 :
  search s (l1 ++ l2) =
  match search s l1 with
  | inl t => search t l2
  | _     => search s l1
  end.
Proof.
revert s; induction l1; simpl; intros. easy.
destruct (check s a); [apply IHl1|easy].
Qed.

Theorem search_inr_inv s l x y :
  search s l = inr (x, y) -> In x l /\ ∃t, check t x = inr y.
Proof.
revert s; induction l; simpl; intros. easy.
destruct (check s a) as [t|y'] eqn:Ha.
apply IHl in H; split; [now right|apply H].
inv H; split; [now left|exists s; apply Ha].
Qed.

End Stateful_search.

Arguments search {_ _ _}.

Section Depth_first_search.

Variable node : Type.
Variable adj : node -> list node.
Variable accept : node -> bool.
Hypothesis dec : ∀v w : node, {v = w} + {v ≠ w}.

Notation diff x y := (subtract dec x y).
Notation next v := (remove dec v (adj v)).
Notation Path := (RTC (λ v w, In w (next v))).
Notation Notin l := (λ x, ¬In x l).
Notation Inr x := (∃r, x = inr r).

Fixpoint dfs depth visited v : list node + list node :=
  match depth with
  | 0   => inl visited
  | S n =>
    if in_dec dec v visited then inl visited
    else if accept v then inr []
    else match search (dfs n) (v :: visited) (next v)
    with
    | inl visited'  => inl visited'
    | inr (w, path) => inr (w :: path)
    end
  end.

Definition DFS_path visited path :=
  Path path /\ Forall (Notin visited) path.
Definition DFS_solution visited v path :=
  DFS_path visited (v :: path) /\ accept (last path v) = true.

Section Utilities.

Theorem Inr_inr {X Y} y :
  Inr (@inr X Y y).
Proof.
exists y; reflexivity.
Qed.

Theorem DFS_solution_refl visited v :
  ¬In v visited /\ accept v = true <-> DFS_solution visited v [].
Proof.
split.
- repeat split. apply RTC_refl.
  apply Forall_cons; easy. simpl; apply H.
- intros [[]]; inv H0.
Qed.

Theorem DFS_path_cons visited v w path :
  DFS_path visited (w :: path) /\ ¬In v visited /\ In w (next v) <->
  DFS_path visited (v :: w :: path).
Proof.
split.
- intros [[] []]; repeat split.
  apply RTC_cons; easy. apply Forall_cons; easy.
- intros []; inv H; inv H0.
Qed.

Theorem DFS_path_incl vis_a vis_b path :
  (∀v, In v vis_a -> In v vis_b) ->
  DFS_path vis_b path -> DFS_path vis_a path.
Proof.
split. apply H0.
eapply Forall_impl. 2: apply H0.
intros v; apply contra, H.
Qed.

Corollary DFS_solution_cons visited v w path :
  DFS_solution visited w path /\ ¬In v visited /\ In w (next v) <->
  DFS_solution visited v (w :: path).
Proof.
unfold DFS_solution; rewrite <-DFS_path_cons, last_cons; easy.
Qed.

Corollary DFS_global_solution_refl v :
  accept v = true <-> DFS_solution [] v [].
Proof.
rewrite <-DFS_solution_refl; easy.
Qed.

Corollary DFS_global_solution_cons v w path :
  DFS_solution [] w path /\ In w (next v) <->
  DFS_solution [] v (w :: path).
Proof.
rewrite <-DFS_solution_cons; easy.
Qed.

End Utilities.

Section Soundness.

(* Visited nodes are remembered. *)
Lemma dfs_inl_incl n vis_a v vis_z z :
  dfs n vis_a v = inl vis_z -> In z vis_a -> In z vis_z.
Proof.
revert vis_a v vis_z; induction n; simpl; intros. inv H.
destruct (in_dec _); [inv H|].
destruct (accept v); [easy|].
destruct (search _) as [vis_z'|[]] eqn:Hs; [inv H|easy].
remember (v :: vis_a) as vis_b.
assert(In z vis_b) by (subst; apply in_cons, H0).
clear H0 Heqvis_b; revert H Hs; revert vis_b.
induction (next v) as [|w ws]; simpl; intros.
inv Hs. destruct (dfs _) as [vis_c|] eqn:Hw; [|easy].
(* The inclusion relation is preserved over the induction. *)
destruct (in_dec dec z vis_c); [|exfalso].
apply IHws with (vis_b:=vis_c); easy.
apply IHn in Hw; easy.
Qed.

(* Solutions given by dfs are correct. *)
Theorem dfs_sound n vis_a v path :
  dfs n vis_a v = inr path -> DFS_solution vis_a v path.
Proof.
revert vis_a v path; induction n; simpl; intros. easy.
destruct (in_dec _); [easy|].
destruct (accept v) eqn:Hv. inv H.
repeat split; [apply RTC_refl|apply Forall_cons; easy|apply Hv].
destruct (search _) as [|[z from_z]] eqn:Hs; [easy|inv H].
(* Abstract over (v :: vis_a) and (next v). *)
remember (v :: vis_a) as vis_b; remember (next v) as nextv.
assert(∀x, In x vis_a -> In x vis_b) by (intros; subst; apply in_cons, H).
assert(∀x, In x nextv -> In x (next v)) by (subst; easy).
clear Hv Heqvis_b Heqnextv; revert Hs H H0; revert vis_b.
(* Do induction over nextv. *)
induction nextv as [|w ws]; simpl; intros.
easy. destruct (dfs _) as [vis_c|] eqn:Hw.
- apply IHws in Hs. apply Hs.
  intros; eapply dfs_inl_incl. apply Hw. apply H, H1.
  intros; apply H0; right; apply H1.
- inv Hs; apply IHn in Hw.
  apply DFS_solution_cons; split; split.
  eapply DFS_path_incl; [apply H|apply Hw].
  apply Hw. apply n0. apply H0; left; easy.
Qed.

End Soundness.

Section Completeness.

Variable graph : list node.
Hypothesis graph_spec : ∀v, In v graph.

(* Two DFS paths can be appended. *)
Lemma DFS_path_trans visited v path1 path2 :
  DFS_path visited (v :: path1) ->
  DFS_path visited (last path1 v :: path2) ->
  DFS_path visited (v :: path1 ++ path2).
Proof.
intros [H1a H1b] [H2a H2b].
rewrite app_comm_cons; split. eapply RTC_trans with (d:=v).
apply H1a. rewrite last_cons; apply H2a.
apply Forall_app; split; [apply H1b|inv H2b].
Qed.

(* Each new visited node can be reached by a path. *)
Lemma path_to_visited n vis_a v vis_z z :
  dfs n vis_a v = inl vis_z -> ¬In z vis_a -> In z vis_z ->
  ∃path, DFS_path vis_a (v :: path) /\ last path v = z.
Proof.
revert vis_a v vis_z; induction n; simpl; intros. inv H.
destruct (in_dec _); [inv H|].
destruct (accept v); [easy|].
destruct (search _) as [vis_z'|[]] eqn:Hs; [inv H|easy].
(* Discard the case z = v. *)
destruct (dec z v). exists []; subst; repeat split.
apply RTC_refl. apply Forall_cons; easy.
(* Abstract over (v :: vis_a) and (next v). *)
remember (v :: vis_a) as vis_b; remember (next v) as nextv.
assert(¬In z vis_b) by (subst; apply not_in_cons; easy).
assert(∀x, In x vis_a -> In x vis_b) by (intros; subst; apply in_cons, H2).
assert(∀x, In x nextv -> In x (next v)) by (subst; easy).
clear H0 n1 Heqvis_b Heqnextv; revert Hs H H2; revert vis_b.
induction nextv as [|w ws]; simpl; intros. inv Hs.
(* Destruct the recursive call, and check if it visits z. *)
destruct (dfs _) as [vis_c|] eqn:Hw; [|easy].
destruct (in_dec dec z vis_c).
- (* If the recursive call visits z; use IHn. *)
  apply IHn in Hw as [path []]; try easy.
  exists (w :: path); split; [|rewrite last_cons; apply H4].
  apply DFS_path_cons; split. eapply DFS_path_incl; [apply H2|apply H0].
  split. apply n0. apply H3, in_eq.
- (* If it doesn't; use IHnextv. *)
  apply IHws with (vis_b:=vis_c); try easy.
  intros; apply H3; apply in_cons, H0.
  intros; eapply dfs_inl_incl. apply Hw. apply H2, H0.
Qed.

(* If a solution exists, then, given enough fuel, dfs will also find one. *)
Theorem dfs_complete vis_a n :
  length (diff graph vis_a) <= n ->
  ∀v path, DFS_solution vis_a v path -> Inr (dfs n vis_a v).
Proof.
revert vis_a; induction n; intros vis_a Hn; intros.
(* Zero case. Contradition since v ∈ graph \ visited. *)
destruct H as [[_ H]]; inv H.
exfalso; apply in_nil with (a:=v).
apply Nat.le_0_r, length_zero_iff_nil in Hn.
rewrite <-Hn; apply subtract_spec; easy.
(* Successor case. *)
destruct H as [[]]; inv H0; simpl.
destruct (in_dec _); [easy|]; clear n0.
destruct (accept v) eqn:Hv; [apply Inr_inr|].
(* Get a sub-path without v. *)
destruct split_at_last_instance with (x:=v)(l:=v::path)
as [pre [path' []]]. apply dec. apply in_eq.
rewrite <-last_cons with (d:=v) in H1; rewrite H0 in H, H1.
apply RTC_app_inv in H as [_ H]; rewrite last_app in H1.
assert(Forall (Notin vis_a) path'). {
  destruct pre; inv H0. apply Forall_app in H5 as [_ H5]; inv H5. }
clear H0 H5 path pre.
(* The given path cannot be empty; obtain the next node. *)
inv H3; [simpl in H1; rewrite H1 in Hv; easy|].
inv H; rewrite last_cons in H1; apply in_remove in H9 as ?.
rename x into w, l into path.
(* Wrap hypotheses back together and clean up. *)
assert(H' : DFS_solution (v :: vis_a) w path). {
  repeat split; try easy. apply Forall_cons.
  apply not_in_cons; easy. apply not_in_cons in H2.
  apply Forall_forall; intros u Hu [F|F]; subst. easy.
  eapply Forall_forall with (x:=u) in H5; easy. }
assert(Hn' : length (diff graph (v :: vis_a)) <= n). {
  simpl; eapply Nat.lt_succ_r, Nat.lt_le_trans.
  apply subtract_length_lt_cons_r; [apply graph_spec|apply H4]. apply Hn. }
clear H H0 H1 H2 H4 H5 H7 Hv Hn.
remember (v :: vis_a) as vis_b; clear Heqvis_b vis_a.
(* Split (next v) into (next1 ++ w :: next2). *)
apply split_list in H9 as [next1 [next2 H9]]; rewrite H9.
cut(Inr (search (dfs n) vis_b (next1 ++ [w]))). intros [[w' path']].
rewrite cons_app, app_assoc, search_app, H; apply Inr_inr.
clear H9 v; revert H' Hn'; revert vis_b.
(* Do induction on the nodes that are checked before w. *)
induction next1 as [|u]; simpl; intros.
- (* At w the previous induction hypothesis guarantees a solution. *)
  apply IHn in H' as [path' H']. rewrite H'; apply Inr_inr. easy.
- (* Check if the search terminates before w. *)
  destruct (dfs _) as [vis_c|] eqn:Hu; [|apply Inr_inr].
  (* If not, then we can use IHnext1. *)
  apply IHnext1; clear IHnext1 next1.
  + (* Show that the path does not go through visited nodes. *)
    destruct H' as [[]]; repeat split; try easy.
    rewrite Forall_Exists_neg, Exists_exists; intros [e [H1e H2e]].
    apply Forall_forall with (x:=e) in H0 as H3e; [|apply H1e].
    (* If it does, then there exists a contradictory solution for v. *)
    eapply path_to_visited in H2e as [to_e ?]; [|apply Hu|apply H3e].
    destruct H2; subst. apply split_list in H1e as [path1 [path2 H1e]].
    rewrite <-last_cons with (d:=w) in H1; rewrite H1e in H, H0, H1.
    apply RTC_app_inv in H as [_ H]; apply Forall_app in H0 as [_ H0];
    rewrite last_app in H1.
    (* to_e ++ path2 is now a solution for u. *)
    assert(DFS_solution vis_b u (to_e ++ path2)).
    * split. apply DFS_path_trans; easy.
      destruct path2. rewrite app_nil_r; apply H1.
      rewrite last_app; rewrite last_cons in H1; apply H1.
    * apply IHn in H3. rewrite Hu in H3; destruct H3; easy. easy.
  + (* Show that n is big enough. *)
    etransitivity; [|apply Hn'].
    apply length_subtract_le_incl_r.
    intros; eapply dfs_inl_incl; [apply Hu|apply H].
Qed.

End Completeness.

Variable upper_bound : nat.
Hypothesis finite_graph : ∃l, length l <= upper_bound /\ ∀v : node, In v l.

Theorem depth_first_search visited v :
  (Σ path, DFS_solution visited v path) +
  {∀path, ¬DFS_solution visited v path}.
Proof.
destruct (dfs upper_bound visited v) as [visited'|path] eqn:H.
- right; intros path Hpath.
  destruct finite_graph as [graph [graph_len graph_spec]].
  assert(Hlen : length (diff graph visited) <= upper_bound).
  + rewrite subtract_length; etransitivity.
    apply Nat.le_sub_l. apply graph_len.
  + eapply dfs_complete with (v:=v) in Hlen as [path' H'].
    congruence. apply graph_spec. apply Hpath.
- left; exists path. eapply dfs_sound, H.
Defined.

End Depth_first_search.

Arguments dfs {_}.
Arguments DFS_path {_}.
Arguments DFS_solution {_}.


Require Import Coq.Classes.Morphisms.
Require Import Coq.ZArith.ZArith.
Require Import Coq.micromega.Lia.
Require Import Crypto.Util.ZUtil.Definitions.
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
Require Import Crypto.Util.ZUtil.Notations.
Local Open Scope Z_scope.

Module Z.
  Lemma combine_at_bitwidth_correct bitwidth lo hi
  : Z.combine_at_bitwidth bitwidth lo hi = lo + (hi << bitwidth).
  Proof. reflexivity. Qed.

  Lemma combine_at_bitwidth_Proper bitwidth
    : Proper (Z.le ==> Z.le ==> Z.le) (Z.combine_at_bitwidth bitwidth).
  Proof.
    cbv [Proper respectful]; intros; rewrite !combine_at_bitwidth_correct.
    destruct bitwidth as [|bitwidth|bitwidth];
      [ | assert (0 <= 2^Z.pos bitwidth) by (apply Z.pow_nonneg; lia).. ];
      rewrite ?Z.shiftl_mul_pow2, ?Z.shiftl_div_pow2, ?Z.pow_0_r by lia; cbn [Z.opp]; try nia;
        Z.div_mod_to_quot_rem; nia.
  Qed.
#[global]
  Hint Resolve combine_at_bitwidth_Proper : zarith.

  Lemma combine_at_bitwidth_Proper1 bitwidth x
    : Proper (Z.le ==> Z.le) (Z.combine_at_bitwidth bitwidth x).
  Proof. repeat intro; eapply combine_at_bitwidth_Proper; (eassumption + reflexivity). Qed.
#[global]
  Hint Resolve combine_at_bitwidth_Proper1 : zarith.

  Lemma combine_at_bitwidth_Proper2 bitwidth x
    : Proper (Z.le ==> Z.le) (fun y => Z.combine_at_bitwidth bitwidth y x).
  Proof. repeat intro; eapply combine_at_bitwidth_Proper; (eassumption + reflexivity). Qed.
#[global]
  Hint Resolve combine_at_bitwidth_Proper2 : zarith.
End Z.


Require Import propInv4.
Require Import verif_cond_2.
Require Import extra2.
Local Open Scope Z.

Theorem proof4_2: (startnewloop hands0 hands1 dryer0 dryer1 ctrlState0 ctrlState1 ctrlTimer0 ctrlTimer1 timer0 timer1) /\ cond2->
 (inv hands1 dryer2 ctrlState2 ctrlTimer2 timer1).

Proof.
intros.
split.
unfold propInv4.
inversion_clear H.
inversion_clear H1.
inversion_clear H2.
inversion_clear H3.
intros.
(*analysis of cases i<timer1 and i=timer1*)
elim Zle_lt_or_eq with i timer1.
intros.
(*prove that dryer1 and dryer2 are equal in all indexes j<timer1*)
assert (Hdryer1_dryer2_same : (forall j, j<timer1 -> dryer1.[of_Z j]=dryer2.[of_Z j])).
intros.
apply arr_same_before_upd with ON timer1.
split; assumption.
rewrite <- Hdryer1_dryer2_same.
rewrite <- Hdryer1_dryer2_same in H5.
apply startnewloop_to_propInv.
assumption.
split.
apply H3.
inversion_clear H0.
auto with zarith.
assumption.
auto with zarith.
assumption.
(*analysis of case i=timer1*)
intros.
rewrite H6.
rewrite H2.
apply get_set_same.
inversion_clear H0.
inversion_clear H8.
inversion_clear H9.
inversion_clear H10.
inversion_clear H11.
rewrite H10.
rewrite length_set.
apply dryer_inf.
inversion_clear H3.
assumption.
apply extra2.
split.
inversion_clear H.
inversion_clear H0.
split.
apply H.
assumption.
apply H.
Qed.


Require Import Omega Arith List Eqdep_dec Program.
Require Import Schema Category Instance Translation.

Set Implicit Arguments.

Set Asymmetric Patterns.

Set Universe Polymorphism.

(** * The empty category *)

Definition empty : Schema.
  refine {| Vertex := Empty_set;
    Edge := fun _ _ => Empty_set;
    PathsEquivalent := (fun _ _ _ _ => True) |};
  abstract (repeat intuition).
Defined.

Definition emptyI : Instance empty.
  refine {| TypeOf := fun x : empty => match x with end;
    FunctionOf := fun _ _ (x : Empty_set) _ => match x with end |};
  abstract destruct s.
Defined.

(** * The Booleans with "implies" edges *)

Definition booleans : Schema.
  refine {| Vertex := bool;
    Edge := (fun b1 b2 => b2 = false \/ b1 = true);
    PathsEquivalent := (fun _ _ _ _ => True) |};
  abstract (repeat intuition).
Defined.

(** * The naturals with >= edges *)

Definition naturals : Schema.
  refine {| Vertex := nat;
    Edge := ge;
    PathsEquivalent := (fun _ _ _ _ => True) |};
  abstract (repeat intuition).
Defined.

(** * Silly functor from Booleans to naturals *)

Definition boolToNat (b : bool) := if b then 1 else 0.

Theorem boolToNat_ge : forall b1 b2, (b2 = false \/ b1 = true)
  -> boolToNat b1 >= boolToNat b2.
  destruct b1; destruct b2; simpl; intuition.
Qed.

Definition booleans_to_naturals : Translation booleans naturals.
  refine {| VertexOf := (boolToNat : booleans -> naturals);
    PathOf := fun _ _ e => AddEdge NoEdges (boolToNat_ge e) |};
  abstract auto.
Defined.

(** Give an instance by interpreting naturals as bitvectors and edges as forgetting of initial bits. *)

Inductive bitvector : nat -> Type :=
| BO : bitvector O
| BS : forall n, bool -> bitvector n -> bitvector (S n).

Fixpoint forget (n m : nat) (bv : bitvector n) : bitvector (n - m) :=
  match bv in bitvector n return bitvector (n - m) with
    | BO => BO
    | BS n' b bv' => match m return bitvector (S n' - m) with
                       | O => BS b bv'
                       | S m' => forget _ bv'
                     end
  end.

Theorem bitvector_case : forall n (bv : bitvector n),
  match n return bitvector n -> Prop with
    | O => fun bv => bv = BO
    | S _ => fun bv => exists b, exists bv', bv = BS b bv'
  end bv.
  destruct bv; eauto.
Qed.

Fixpoint erase n (bv : bitvector n) : list bool :=
  match bv with
    | BO => nil
    | BS _ b bv' => b :: erase bv'
  end.

Theorem erase_eq : forall n (bv bv' : bitvector n),
  erase bv = erase bv'
  -> bv = bv'.
  induction bv; intro bv'; specialize (bitvector_case bv'); firstorder; subst; simpl in *.
  injection H0; intros.
  f_equal; eauto.
Qed.

Fixpoint forget' (m : nat) (bv : list bool) : list bool :=
  match bv with
    | nil => nil
    | b :: bv' => match m with
                    | O => b :: bv'
                    | S m' => forget' m' bv'
                  end
  end.

Theorem forget_forget' : forall n (bv : bitvector n) m,
  erase (forget m bv) = forget' m (erase bv).
  induction bv; destruct m; simpl; intuition.
Qed.

Theorem double_sub : forall n1 n2, n1 >= n2 -> n1 - (n1 - n2) = n2.
  intros; omega.
Qed.

Theorem push_app : forall dom (ran : nat -> Type) n1 n2 (f : dom -> ran n1) x (pf : n1 = n2),
  match pf in _ = N return dom -> ran N with
    | refl_equal => f
  end x = match pf in _ = N return ran N with
            | refl_equal => f x
          end.
  intros; subst; reflexivity.
Qed.

Theorem push_erase : forall n1 n2 (Heq : n1 = n2) bv,
  erase (match Heq in _ = N return bitvector N with
           | refl_equal => bv
         end) = erase bv.
  intros; subst; reflexivity.
Qed.

Theorem double_forget' : forall m2 bv m1,
  forget' m2 (forget' m1 bv) = forget' (m1 + m2) bv.
  induction bv; destruct m1; simpl; intuition.
  induction m2; auto.
Qed.

Lemma path_ge : forall n1 n2, path' ge n1 n2 -> n1 >= n2.
  induction 1; simpl; intuition.
Qed.

Lemma compose_unique' : forall n1 n2 (p : path' ge n1 n2) bv,
  erase (compose bitvector (fun n1 n2 pf => match double_sub pf in _ = N return _ -> bitvector N with
                                              | refl_equal => @forget n1 (n1 - n2)
                                            end) p bv)
  = erase (forget (n1 - n2) bv).
  induction p; simpl; intuition.

  rewrite minus_diag.
  destruct bv; reflexivity.

  rewrite push_app.
  rewrite push_erase.
  repeat rewrite forget_forget'.
  rewrite IHp.
  rewrite forget_forget'.
  rewrite <- forget_forget'.
  rewrite forget_forget'.
  rewrite double_forget'.
  f_equal.
  specialize (path_ge p).
  omega.
Qed.

Lemma compose_unique : forall n1 n2 Heq (p : path' ge n1 n2) bv,
  compose bitvector (fun n1 n2 pf => match double_sub pf in _ = N return _ -> bitvector N with
                                       | refl_equal => @forget n1 (n1 - n2)
                                     end) p bv
  = match Heq in _ = N return bitvector N with
      | refl_equal => forget (n1 - n2) bv
    end.
  intros; apply erase_eq.
  rewrite compose_unique'.
  generalize (forget (n1 - n2) bv), Heq.
  rewrite Heq; intros.
  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).
  reflexivity.
Qed.

Definition bitvectors : Instance naturals.
  refine {| TypeOf := (bitvector : Vertex naturals -> _);
    FunctionOf := (fun n1 n2 pf => match double_sub pf in _ = N return _ -> bitvector N with
                                     | refl_equal => @forget n1 (n1 - n2)
                                   end) |}.
  abstract (intros; assert (Heq : s - (s - d) = d) by (specialize (path_ge p1); omega);
    repeat rewrite (compose_unique Heq); reflexivity).
Defined.

(** * A sample schema and database *)

Inductive emailsV :=
| SelfEmails
| Emails
| People.

Inductive emailsE : emailsV -> emailsV -> Type :=
| SelfEmails_Emails : emailsE SelfEmails Emails
| Sender : emailsE Emails People
| Receiver : emailsE Emails People.

Inductive emailsEq : forall s d, path' emailsE s d -> path' emailsE s d -> Prop :=
| Refl : forall s d (p : path' emailsE s d), emailsEq p p
| Law : emailsEq (AddEdge (AddEdge NoEdges SelfEmails_Emails) Sender)
  (AddEdge (AddEdge NoEdges SelfEmails_Emails) Receiver)
| LawSymm : emailsEq (AddEdge (AddEdge NoEdges SelfEmails_Emails) Receiver)
  (AddEdge (AddEdge NoEdges SelfEmails_Emails) Sender).

Hint Constructors emailsEq.

Inductive selfEmailId := S181.
Inductive emailId := E180 | E181.
Inductive person := Bob | Sue | David.

Ltac dep_destruct H := generalize H; intro H'; dependent destruction H'.

Ltac destructor := simpl; intuition;
  repeat (match goal with
            | [ H : ?T |- _ ] =>
              match eval hnf in T with
                | emailsEq ?X ?Y =>
                  match goal with
                    | [ x : _ |- _ ] =>
                      match x with
                        | X => hnf in H; dep_destruct H
                        | Y => hnf in H; dep_destruct H
                      end
                  end
                | emailsE _ _ => dep_destruct H
                | selfEmailId => destruct H
              end
          end; simpl in *); auto.

Definition emailsSchema : Schema.
  refine {| Vertex := emailsV;
    Edge := emailsE;
    PathsEquivalent := emailsEq
    |}; abstract (repeat destructor; try split; hnf; destructor).
Defined.

Definition emailsTypeof (v : emailsSchema) : Set :=
  match v with
    | SelfEmails => selfEmailId
    | Emails => emailId
    | People => person
  end.

Definition emailsInstance : Instance emailsSchema.
  refine {| TypeOf := emailsTypeof;
    FunctionOf := (fun s d (E : Edge emailsSchema s d) =>
      match E in emailsE s d return emailsTypeof s -> emailsTypeof d with
        | SelfEmails_Emails => fun id => match id with
                                           | S181 => E181
                                         end
        | Sender => fun id => match id with
                                | E180 => Bob
                                | E181 => David
                              end
        | Receiver => fun id => match id with
                                  | E180 => Sue
                                  | E181 => David
                                end
      end)
   |}; abstract destructor.
Defined.


Require Import XR_Rinv_r.
Require Import XR_Rmult_1_l.

Local Open Scope R_scope.

Lemma Rinv_r_simpl_r : forall r1 r2, r1 <> R0 -> r1 * / r1 * r2 = r2.
Proof.
  intros x y h.
  rewrite Rinv_r.
  {
    rewrite Rmult_1_l.
    reflexivity.
  }
  { exact h. }
Qed.


Require Import Coq.Program.Tactics.
Require Import Coq.Program.Equality.
Require Import LibLN.
Require Import STLCNew.
Require Import CoherenceBasicBDNew.
Require Import STLCred.

Inductive VChk : PExp -> PTyp -> Prop :=
  | VLam : forall A B t, VChk (PLam t) (Fun A B).

Inductive VInf : PExp -> PTyp -> Prop :=
  | VInt : forall n, VInf (PLit n) PInt
  | VMerge : forall v1 v2 A B, VInf v1 A ->
                          VInf v2 B ->
                          VInf (PMerge v1 v2) (And A B)
  | VAnn : forall v A, VChk v A -> VInf (PAnn v A) A.

Hint Constructors VChk VInf.

Definition value (v : PExp) := exists A, VInf v A.

Inductive subred : PExp -> PExp -> PTyp -> Prop :=
  | SRed_Fun :
      forall v A B C D,
        VInf v (Fun A B) ->
        subred v (PAnn (PLam (PAnn (PApp v (PBVar 0)) D)) (Fun C D)) (Fun C D)
  | SRed_AndR : forall v A B, value v ->
                         subred v (PMerge (PAnn v A) (PAnn v B)) (And A B)
  | SRed_AndL1 : forall v1 v2 A B, VInf v1 B ->
                              value v2 ->
                              Atomic A ->
                              Sub B A ->
                              subred (PMerge v1 v2) v1 A
  | SRed_AndL2 : forall v1 v2 A C, value v1 ->
                              VInf v2 C ->
                              Atomic A ->
                              Sub C A ->
                              subred (PMerge v1 v2) v2 A.

Inductive bired : PExp -> PExp -> Prop :=
  | Red_App1 : forall e1 e2 e3,
                 bired e1 e3 ->
                 bired (PApp e1 e2) (PApp e3 e2)
  | Red_App2 : forall e1 e2 v,
                 value v ->
                 bired e1 e2 ->
                 bired (PApp v e1) (PApp v e2)
  | Red_App3 : forall A B C v1 v2 e,
                 VInf v1 (Fun A B) ->
                 VInf v2 C ->
                 A <> C ->
                 subred v2 e A ->
                 bired (PApp v1 v2) (PApp v1 e)
  | Red_App4 : forall A B e v,
                 VChk v A ->
                 bired (PApp (PAnn (PLam e) (Fun A B)) v)
                       (PAnn (open_source e (PAnn v A)) B)
  | Red_App5 : forall A B e v,
                 VInf v A ->
                 bired (PApp (PAnn (PLam e) (Fun A B)) v)
                       (PAnn (open_source e v) B)
  | Red_Merge1 : forall e1 e2 e3,
                   bired e1 e3 ->
                   bired (PMerge e1 e2) (PMerge e3 e2)
  | Red_Merge2 : forall e1 e2 v,
                   value v ->
                   bired e1 e2 ->
                   bired (PMerge v e1) (PMerge v e2)
  | Red_Ann1 : forall e1 e2 A,
                 bired e1 e2 ->
                 bired (PAnn e1 A) (PAnn e2 A)
  | Red_Ann2 : forall v e A B,
                 VInf v B ->
                 A <> B ->
                 subred v e A ->
                 bired (PAnn v A) (PAnn e A)
  | Red_Ann3 : forall v A, VInf v A ->
                      bired (PAnn v A) v.

Hint Constructors WFTyp subred bired.

(* We didn't prove this before?! See: Pfenning *)
Theorem sub_trans : forall A B, Sub A B -> forall C, Sub B C -> Sub A C. Admitted.

Hint Resolve reflex sub_trans.
Hint Unfold Sub.

Hint Unfold erase.

Theorem VInf_bityping_eq :
  forall A v, VInf v A -> forall B Gamma, bidityping Gamma v Inf B -> A = B.
Proof.
  intros A v HIn.
  induction HIn; eauto 3.
  - intros; inversion H; subst; eauto.
  - intros; inversion H; subst.
    erewrite IHHIn1; erewrite IHHIn2; eauto.
  - intros; now inversion H0; subst.
Qed.

Hint Resolve VInf_bityping_eq.

Theorem VInf_bityping_sub :
  forall A v, VInf v A -> forall B Gamma m, bidityping Gamma v m B -> Sub A B.
Proof.
  intros A v HIn.
  induction HIn.
  - intros; inversion H; subst; auto.
    inversion H0; subst; eauto.
  - intros; dependent induction H; [ clear IHbidityping1 IHbidityping2 | eauto 5 ].
    apply sand1; [ apply sand2 | apply sand3 ]; eauto.
  - intros; inversion H; subst; auto.
    inversion H0; subst; eauto.
    inversion H1; subst; eauto.
Qed.

Hint Resolve VInf_bityping_sub.

Theorem bityping_inf_chk :
  forall Gamma e A,
    bidityping Gamma e Inf A -> bidityping Gamma e Chk A.
Proof.
  intros Gamma e A Htyping.
  assert (Ha : Sub A A) by eauto; destruct Ha.
  eapply ATySub' with (A := A); eauto.
Qed.

Hint Resolve bityping_inf_chk.

(** Theorem 1. Subject reduction **)

Theorem subject_reduction_sub' :
  forall Gamma v A, bidityping Gamma v Inf A ->
           forall e B, subred v e B ->
                  Sub A B ->
                  WFTyp B ->
                  bidityping Gamma e Inf B.
Proof.
  intros Gamma v A Htyping e B Hred HTyp.
  generalize dependent Gamma.
  induction Hred; intros.
  - inverts H. dependent induction Htyping; subst; eauto; clear IHHtyping.
    inverts H0.
    assert (Ha1 : Sub (Fun C D) (Fun C D)). eauto. destruct Ha1.
    apply ATyAnnCT'.
    assert (Ha : WFTyp (Fun A0 B)) by
        (now assert (Ha := bityping_wf Htyping); inversion Ha).
    inverts Ha.
    apply_fresh ATyLam' as x; auto.
    unfold open_source; simpl.
    case_nat*.
    assert (Ha2 : Sub D D) by eauto; destruct Ha2.
    eapply ATySub' with (A := D); eauto 2.
    apply ATyAnnCT'.
    inverts HTyp; inverts H2.
    eapply ATySub' with (A := B); eauto 2.
    eapply ATyApp' with (A := A0).
    + apply ATyAnnCT'.
      rewrite <- open_rec_source_term; eauto 3.
      rewrite <- concat_empty_r with (E := Gamma & y ~ C).
      apply bityping_weaken; rewrite concat_empty_r; autos*.
    + assert (Ha1 : Sub C C) by apply reflex; destruct Ha1.
      eapply ATySub' with (A := C); eauto 2.
      apply* ATyVar'.
  - inverts H.
    inverts HTyp. inverts H; try now inversion H3.
    inverts H0.
    assert (Ha : Sub (And A0 B) (And A0 B)) by eauto.
    destruct Ha.
    apply* ATyMerge'.
  - dependent induction Htyping; subst; eauto. clear IHHtyping1 IHHtyping2.
    assert (B = A) by eauto; subst. admit.
  - dependent induction Htyping; subst; eauto. clear IHHtyping1 IHHtyping2.
    assert (C = B) by eauto; subst. admit.
Admitted.

Theorem subject_reduction_sub :
  forall Gamma v A, bidityping Gamma v Inf A ->
           forall e B, subred v e B ->
                  Sub A B ->
                  WFTyp B ->
                  bidityping Gamma e Chk B.
Proof.
  intros Gamma v A Htyping e B Hred HTyp.
  generalize dependent Gamma.
  induction Hred; intros.
  - inverts H. dependent induction Htyping; subst; eauto; clear IHHtyping.
    inverts H0.
    assert (Ha1 : Sub (Fun C D) (Fun C D)). eauto. destruct Ha1.
    apply ATySub' with (A := Fun C D) (C := x); eauto.
    apply ATyAnnCT'.
    assert (Ha : WFTyp (Fun A0 B)) by
        (now assert (Ha := bityping_wf Htyping); inversion Ha).
    inverts Ha.
    apply_fresh ATyLam' as x; auto.
    unfold open_source; simpl.
    case_nat*.
    assert (Ha2 : Sub D D) by eauto; destruct Ha2.
    eapply ATySub' with (A := D); eauto 2.
    apply ATyAnnCT'.
    inverts HTyp; inverts H2.
    eapply ATySub' with (A := B); eauto 2.
    eapply ATyApp' with (A := A0).
    + apply ATyAnnCT'.
      rewrite <- open_rec_source_term; eauto 3.
      rewrite <- concat_empty_r with (E := Gamma & y ~ C).
      apply bityping_weaken; rewrite concat_empty_r; autos*.
    + assert (Ha1 : Sub C C) by apply reflex; destruct Ha1.
      eapply ATySub' with (A := C); eauto 2.
      apply* ATyVar'.
  - inverts H.
    inverts HTyp. inverts H; try now inversion H3.
    inverts H0.
    assert (Ha : Sub (And A0 B) (And A0 B)) by eauto.
    destruct Ha.
    apply* ATySub'.
    apply* ATyMerge'.
  - dependent induction Htyping; subst; eauto. clear IHHtyping1 IHHtyping2.
    assert (B = A) by eauto; subst. destruct H2; apply* ATySub'.
  - dependent induction Htyping; subst; eauto. clear IHHtyping1 IHHtyping2.
    assert (C = B) by eauto; subst. destruct H2; apply* ATySub'.
Qed.

Theorem subject_reduction :
  forall Gamma e1 A m, bidityping Gamma e1 m A ->
              forall e2, bired e1 e2 ->
                    bidityping Gamma e2 m A.
Proof.
  intros Gamma e1 A m Htyping e2 Hred;
  generalize dependent A; generalize dependent Gamma; generalize dependent m.
  induction Hred; intros; try now (dependent induction Htyping; subst; eauto).
  - (* R_App3 *)
    dependent induction Htyping; subst; eauto; clear IHHtyping1 IHHtyping2.
    inversion H; subst; inversion Htyping1; subst.
    apply ATyApp' with (A := A0); auto.
    inverts Htyping2. inverts H0.
    assert (Ha : C = A) by eauto; subst.
    apply* subject_reduction_sub.
  - (* R_App4 *)
    dependent induction Htyping; eauto; clear IHHtyping1 IHHtyping2.
    inverts* Htyping1.
    apply ATyAnnCT'. inverts H.
    inverts H4.
    eapply open_body_bityping; eauto.
    inverts H.
  - (* R_App5 *)
    dependent induction Htyping; subst; eauto.
    clear IHHtyping1 IHHtyping2.
    inversion Htyping1; subst.
    apply ATyAnnCT'; clear Htyping1.
    apply open_body_bityping with (A := A0); eauto.
    inversion H4; subst; eauto.
    inversion H0.
    dependent induction Htyping2; subst; eauto.
    inversion H2.
    assert (B = A) by eauto; now subst.
  - (* R_Ann2 *)
    dependent induction Htyping; eauto; subst; clear IHHtyping.
    inverts Htyping. inverts H.
    apply ATyAnnCT'; apply* subject_reduction_sub.
  - (* R_Ann3 *)
    dependent induction Htyping; eauto; clear IHHtyping.
    inverts Htyping. inverts H.
    assert (A = A0) by eauto; now subst.
Qed.

(** Theorem 2. Reduction is deterministic **)

Hint Extern 1 =>
  match goal with
    | [ H : bired (PLam ?e2) ?e1 |- _ ] => inversion H
    | [ H : VInf (PLam ?e) ?A |- _ ] => inversion H
    | [ H : VInf (PInt ?e) ?A |- _ ] => inversion H
  end.

Lemma value_inf_chk_false : forall v A B, VChk v A -> VInf v B -> False.
Proof.
  introv H1 H2; inverts H1; inverts H2.
Qed.

Hint Resolve value_inf_chk_false.

Lemma value_not_red : forall e1 e2 A, VInf e1 A -> bired e1 e2 -> False.
Proof.
  intros e1 e2 A Hin Hred. generalize dependent A.
  induction Hred; intros; try now inversion Hin; subst; eauto.
  inverts Hin. inverts H2. inverts Hred.
Qed.

Hint Extern 1 =>
  match goal with
    | [ H1 : VInf ?e1 ?A,
        H2 : bired ?e1 ?e2 |- _ ] => exfalso; apply (value_not_red _ _ _ H1 H2)
    | [ H1 : value ?v,
        H2 : bired ?e1 ?e2 |- _ ] => destruct H1 as [HHH1 HHH2]; exfalso;
                                    apply (value_not_red _ _ _ HHH1 H2)
  end.

Lemma VInf_unique : forall v A B, VInf v A -> VInf v B -> A = B.
Proof.
  intros v A B HIn1 HIn2. generalize dependent B.
  induction HIn1; intros; inversion HIn2; subst; auto.
  apply IHHIn1_1 in H1; apply IHHIn1_2 in H3; now subst.
Qed.

Hint Rewrite VInf_unique.
Hint Resolve value_not_red.

Hint Extern 1 =>
  match goal with
    | [ H : VInf (PLam ?e) ?A |- _ ] => inverts H
    | [ H : bired (PLam ?e1) ?e2 |- _ ] => inverts H
  end.

Theorem subred_unique : forall v e1 A, subred v e1 A -> forall e2 Gamma, subred v e2 A ->
                                                          bidityping Gamma v Chk A -> e1 = e2.
Proof.
  introv Hred1.
  induction Hred1; introv Hred2 Typ.
  - inverts H. inverts* Hred2.
  - inverts* Hred2. inverts H2. inverts H2.
  - inverts* Hred2. inverts H3. inverts H1.
    inverts Typ. inverts H3.
    assert (Ha1 : B = A1) by eauto.
    assert (Ha2 : C = B0) by eauto. substs.
    assert (Ha3 : Sub (And A1 B0) A) by eauto.
    lets* Ha4 : uniquesub H15 Ha3.
  - inverts* Hred2. inverts H3. inverts H1.
    inverts Typ. inverts H3.
    assert (Ha1 : B = A1) by eauto.
    assert (Ha2 : C = B0) by eauto. substs.
    assert (Ha3 : Sub (And A1 B0) A) by eauto.
    lets* Ha4 : uniquesub H15 Ha3.
Qed.

Theorem bired_unique :
  forall e1 e2, bired e1 e2 -> forall e3, bired e1 e3 -> forall Gamma A m,
                                               bidityping Gamma e1 m A -> e2 = e3.
Proof.
  introv Hred.
  induction Hred; intros.
  - dependent induction H0; eauto; clear IHbidityping1 IHbidityping2.
    inverts* H.
    + forwards* Ha : IHHred; substs*.
    + destruct H2; tryfalse*.
    + inverts H0_; inverts* Hred.
    + inverts* Hred.
  - dependent induction H1; eauto; clear IHbidityping1.
    inverts* H0.
    + destruct* H.
    + forwards* Ha : IHHred; substs*.
    + inverts* H4.
  - dependent induction H4; eauto; clear IHbidityping1 IHbidityping2.
    inverts* H3.
    + assert (Ha1 : Fun A1 B1 = Fun A B). apply VInf_unique with (v := v1); auto.
      assert (Ha2 : Fun A1 B1 = Fun A0 B0) by eauto.
      inverts Ha1; inverts Ha2.
      lets* Ha : subred_unique H2 H10 H4_0; substs*.
    + tryfalse*.
    + inverts H. assert (C = A) by apply* VInf_unique. substs*.
  - dependent induction H1; eauto; clear IHbidityping1 IHbidityping2.
    inverts H1_. inverts H0; tryfalse*. auto.
  - dependent induction H1; eauto; clear IHbidityping1 IHbidityping2.
    inverts* H0.
    + inverts* H4.
    + inverts H3. assert (C = A1) by apply* VInf_unique. substs*.
    + tryfalse*.
  - dependent induction H0; eauto; clear IHbidityping1 IHbidityping2.
    inverts H.
    forwards* Ha : IHHred. substs*.
    destruct H3.
    tryfalse*.
  - dependent induction H1; eauto; clear IHbidityping1 IHbidityping2.
    inverts H0. destruct* H. forwards* Ha : IHHred. substs*.
  - dependent induction H0; eauto.
    inverts* H.
    forwards* Ha : IHHred; substs*.
  - dependent induction H3; eauto; clear IHbidityping.
    inverts* H2.
    lets* Ha : subred_unique H1 H9 H3; substs*.
    assert (A = B) by apply* VInf_unique. substs*.
  - dependent induction H1; eauto; clear IHbidityping.
    inverts* H0.
    assert (A = B) by apply* VInf_unique. substs*.
Qed.

(** Theorem 3. Reduction is complete **)

(*
Lemma value_ann_red_id :
  forall v A e, In v A -> red (PAnn CT v A) e -> v = e.
Proof.
  intros v A e Hin Hred.
  dependent induction Hred; eauto.
  - inversion Hin; subst; exfalso. now apply H.
  - inversion Hin; subst; inversion H0.
  - inversion Hin; subst; inversion H0.
  - inversion Hin; subst.
    assert (Ha : And C D = And A0 B) by (eapply In_unique; eauto).
    inversion Ha; subst; contradiction.
Qed.

Hint Rewrite value_ann_red_id.
 *)

Hint Constructors equiv_.
Hint Resolve fullred_regular.

Lemma fullred_equiv_regular :
  forall e1 e2, equiv_ fullred e1 e2 -> STTerm e1 /\ STTerm e2.
Proof. introv H; induction* H. Qed.

Lemma fullred_equiv_regular_l :
  forall e1 e2, equiv_ fullred e1 e2 -> STTerm e1.
Proof. introv H; forwards* Ha : fullred_equiv_regular e1 e2. Qed.

Lemma fullred_equiv_regular_r :
  forall e1 e2, equiv_ fullred e1 e2 -> STTerm e2.
Proof. introv H; forwards* Ha : fullred_equiv_regular e1 e2. Qed.

Hint Resolve fullred_equiv_regular_l fullred_equiv_regular_r.

Lemma fullred_equiv_app_l :
  forall e1 e2, equiv_ fullred e1 e2 ->
           forall e3, STTerm e3 ->
                 equiv_ fullred (STApp e1 e3) (STApp e2 e3).
Proof. introv Equiv; induction* Equiv. Qed.

Lemma fullred_equiv_app_r :
  forall e2 e3, equiv_ fullred e2 e3 ->
           forall e1, STTerm e1 ->
                 equiv_ fullred (STApp e1 e2) (STApp e1 e3).
Proof. introv Equiv; induction* Equiv. Qed.

Hint Resolve fullred_equiv_app_l fullred_equiv_app_r.

Lemma fullred_equiv_pair_l :
  forall e1 e2, equiv_ fullred e1 e2 ->
           forall e3, STTerm e3 ->
                 equiv_ fullred (STPair e1 e3) (STPair e2 e3).
Proof. introv Equiv; induction* Equiv. Qed.

Lemma fullred_equiv_pair_r :
  forall e2 e3, equiv_ fullred e2 e3 ->
           forall e1, STTerm e1 ->
                 equiv_ fullred (STPair e1 e2) (STPair e1 e3).
Proof. introv Equiv; induction* Equiv. Qed.

Lemma fullred_equiv_pair :
  forall e1 e3, equiv_ fullred e1 e3 ->
           forall e2 e4, equiv_ fullred e2 e4 ->
                 equiv_ fullred (STPair e1 e2) (STPair e3 e4).
Proof.
  introv H1 H2.
  apply equiv_trans with (t2 := (STPair e3 e2)).
  apply* fullred_equiv_pair_l.
  apply* fullred_equiv_pair_r.
Qed.

Hint Resolve fullred_equiv_pair_l fullred_equiv_pair_r fullred_equiv_pair.

Lemma subred_equiv : forall v t A,
              subred v t A ->
              forall E1 E2,
                has_type_source_alg empty v Chk A E1 ->
                has_type_source_alg empty t Chk A E2 ->
                equiv_ fullred E1 E2.
Proof.
  introv Subred.
  induction Subred; introv Typ1 Typ2.
  - inverts H; inverts H0.
    inverts Typ1; inverts Typ2.
    inverts H.
    inverts H2.
    inverts H3.
    inverts H0.
    inverts H6; inverts H7; try now inverts H.
    admit.
  - inverts Typ1. inverts Typ2.
    inverts H3.
    inverts H1; try now inverts H6.
    inverts H4; try now inverts H14.
    inverts H.
    inverts H8. inverts H10.
    assert (x = A0) by eauto. substs.
    inverts* H4. inverts* H6.
    assert (A0 = A) by eauto. substs.
    assert (A = A1) by eauto. symmetry in H6; substs.
    assert (C0 = c2). apply @sub_coherent with (A := A) (B := B0); eauto.
    assert (C = c1). apply @sub_coherent with (A := A) (B := A2); eauto. substs.
    assert (E1 = E) by apply* typ_coherence.
    assert (E0 = E) by apply* typ_coherence. substs.
    clear H2 H5 H9 H10 H0 H4.
    admit.
  - inverts Typ1; inverts Typ2.
    inverts H.
    assert (B = A1) by eauto. substs.
    inverts H3.
    assert (A1 = A2) by eauto. substs.
    assert (E1 = E0). eapply typ_coherence; eauto. substs.
    inverts H4.
    inverts H1.
    assert (Ha : WFTyp A2) by eauto.
    assert (c = C0). eapply sub_coherent. apply Ha. apply H5. auto. auto. substs.
    admit. (* seems provable *)
    assert (Ha : Sub (And A2 B) A) by eauto.
    lets Ha1 : uniquesub H14 Ha.
    destruct Ha1; unfold Sub; split; eauto.
  - inverts Typ1; inverts Typ2.
    inverts H0.
    assert (C = A1) by eauto. substs.
    inverts H3.
    assert (A1 = B) by eauto. substs.
    assert (E2 = E0). eapply typ_coherence; eauto. substs.
    inverts H4.
    inverts H1.
    assert (Ha : Sub (And A2 B) A) by eauto.
    lets Ha1 : uniquesub H14 Ha.
    destruct Ha1; unfold Sub; split; eauto.
    assert (Ha : WFTyp B) by eauto.
    assert (c = C1). eapply sub_coherent. apply Ha. apply H5. auto. auto. substs.
    admit. (* seems provable *)
Admitted.

Definition id := STLam (STBVar 0).
Definition idType a := STFun a a.

Definition app := STLam (STLam (STApp (STBVar 1) (STBVar 0))).
Definition appType a b := STFun (STFun a b) (STFun a b).

Lemma app_id :
  forall A B,
    has_type_st empty app (appType A B) ->
    forall f, has_type_st empty f (STFun A B) ->
         STValue f ->
         equiv_ fullred (STApp app f) f.
Proof.
  introv Typ1 Typ2 Value.
  inverts Value; inverts Typ2.
  unfold app.
  apply* equiv_trans.
  unfold open; simpls; repeat case_nat.

Admitted.

Lemma consistency_fullred :
  forall e A c1 m, has_type_source_alg empty e m A c1 ->
              forall e', bired e e' ->
                    forall c2, has_type_source_alg empty e' m A c2 ->
                         equiv_ fullred c1 c2.
Proof.
  introv Typ.
  gen_eq E: (empty:env PTyp). lets Typ': Typ.
  induction* Typ; intros; substs.
  - inverts* H3.
  - inverts* H2; inverts H1.
  - inverts* H0.
    + inverts* H1.
      assert (HH : exists c, has_type_source_alg empty e3 Inf (Fun A B) c).
      apply soundness; apply completeness in Typ1; lets* Ha : subject_reduction Typ1.
      destruct HH.
      assert (Ha : Fun A0 B = Fun A B) by (eapply typ_inf_unique; eauto); inverts Ha; clear H.
      assert (E2 = E3) by apply* typ_coherence; subst.
      lets* Ha1 : IHTyp1 Typ1 H4 H3.
    + inverts H3; inverts H. inverts H1. inverts Typ1.
      inverts H1.
      inverts H6.
      inverts H1.
      inverts H4.
      inverts Typ1.
      lets* Ha1 : IHTyp2 Typ2 H5 H6.
      assert (E0 = E1) by apply* typ_coherence; subst.
      lets Ha2 : type_preservation H6.
      unfold conv_context in Ha2; rewrite map_empty in Ha2. eauto.
    + inverts H3.
      inverts Typ1.
      inverts H.
      inverts H1.
      inverts H3.
      clear IHTyp1 IHTyp2.
      assert (E1 = E0) by (eapply typ_coherence; eauto).
      subst.
      apply* fullred_equiv_app_r.

      inverts Typ2. inverts H4.
      assert (Ha : exists E4, has_type_source_alg empty e Inf A E4). admit.
      destruct Ha.
      inverts H6.
      inverts H2.
      forwards* Ha : typ_unique H2 H3. destruct Ha.
      assert (x = E1). apply* typ_coherence. substs.
      assert (C1 = C0). apply @sub_coherent with (A := A) (B := A0); eauto. substs.

      admit. (* property about subred ? *)
    + clear IHTyp1 IHTyp2.
      inverts Typ1.
      inverts H1; clear H5.
      inverts H4.
      admit. (* beta reduction *)
    + clear IHTyp1 IHTyp2.
      inverts Typ1.
      admit. (* beta reduction *)
  - inverts H1; inverts H2.
    + lets* Ha1 : IHTyp1 Typ1 ___ H7.
      assert (E2 = E3) by apply* typ_coherence; substs*.
    + lets* Ha1 : IHTyp2 Typ2 ___ H9.
      assert (E1 = E0) by apply* typ_coherence; substs*.
  - inverts H0.
    + inverts H1; forwards* Ha : IHTyp Typ.
    + inverts H1.
      admit. (* property about subred ? *)
    + inverts Typ.
      inverts H1.
      clear IHTyp.
      inverts Typ'; clear H8.
      assert (Ha : A = A0) by eauto. symmetry in Ha; subst.
      assert (c2 = E0). eapply typ_coherence; eauto. subst; clear H1.
      admit. (* induction H0 and discharge cases using H4? *)
  - lets* Ha : IHTyp Typ H2.
    inverts H3.
    inverts* H2.
    assert (A = A0).
    lets* Ha1 : completeness Typ.
    lets* Ha2 : subject_reduction Ha1 H2.
    apply soundness in Ha2; destruct Ha2; eapply typ_inf_unique; eauto.
    subst.
    lets* Ha3 : Ha H1.
    assert (C0 = C).
    eapply @sub_coherent with (B := B) (A := A0); auto; apply* typing_wf_source_alg.
    subst.
    lets* Ha4 : type_correct_coercions H4 ___.
Admitted.


From Undecidability.L Require Export Datatypes.LBool Datatypes.LNat Datatypes.LTerm.
Require Import Nat.
From Undecidability.L Require Import Tactics.LTactics Functions.EqBool.
Import EqBool.
(* * Extracted Functions *)

(* ** Extracted equality of encoded terms *)

Fixpoint term_eqb s t :=
  match s,t with
  | var n, var m => eqb n m
  | L.app s1 t1, L.app s2 t2 => andb (term_eqb s1 s2) (term_eqb t1 t2)
  | lam s',lam t' => term_eqb s' t'
  | _,_ => false
  end.

Lemma term_eqb_spec : forall x y1 : term, reflect (x = y1) (term_eqb x y1).
Proof with try (constructor;congruence).
  induction x;cbn; destruct y1...
  - destruct (eqb_spec n n0)...
  -destruct (IHx1 y1_1)...
   destruct (IHx2 y1_2)...
  -destruct (IHx y1)...
Qed.

#[global]
Instance eqbTerm : eqbClass term_eqb.
Proof.
  exact term_eqb_spec.
Qed.

Global
Instance eqbComp_nat : eqbComp term.
Proof.
  constructor. unfold term_eqb.
  extract.
Qed.