text:
(** * 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".
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 o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.

(** Here, we could finish with "[rewrite -> eq2.  reflexivity.]" as we
    have done several times before.  We can finish this proof 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 ->
    (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 n, evenb n = true -> oddb (S n) = true) ->
     evenb 2 = true ->
     oddb 3 = true.
Proof.
  intros H eq1.
  apply H. apply eq1.
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 = (n =? 5)  ->
     (S (S n)) =? 7 = true.
Proof.
  intros n H.

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

  symmetry.
  simpl. (** (This [simpl] is optional, since [apply] will perform
             simplification first, if needed.) *)
  apply H.  Qed.

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

    _Hint_: You can 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). *)

Theorem rev_exercise1 : forall (l1 l2 : list nat),
     l1 = rev l2 ->
     l2 = rev l1.
Proof.
  intros l1 l2.
  destruct l1 as [|x l1'].
  - intro. rewrite H. symmetry. apply rev_involutive.
  - intro. 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?

Rewrite (H: x = y) substitutes "x" in the goal with "y".

Apply (H: x = y) replaces the goal "s = t" directly with "x = y".
If there is a condition, the condition will be restated as a new goal.
*)

(* ################################################################# *)
(** * 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, we usually don't have to include the name [m] in
    the [with] clause; Coq is often smart enough to figure out which
    variable we are instantiating. We could instead write [apply
    trans_eq with [c;d]].) *)

(** Coq also has a 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.
  transitivity m.
  - apply H0.
  - apply H.
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 more
    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 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 different.  (Since [true] and
    [false] take no arguments, their injectivity is neither here
    nor there.)  And so on. *)

(** For example, 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. 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.
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** Alternatively, if you just say [injection H] with no [as] clause,
    then all the equations will be turned into hypotheses at the
    beginning of the goal. *)

Theorem injection_ex2 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H.
  injection H.
  (* WORKED IN CLASS *)
  intros H1 H2. rewrite H1. rewrite H2. reflexivity.
Qed.

(** **** 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.
  injection H. intros.
  transitivity z.
  - assumption.
  - rewrite H0 in H1. injection H1 as H3. symmetry. apply H3.
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., [S n = O]), and it solves the current goal
    immediately.  Here is an example: *)

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.

(** This is an instance of a logical principle known as the _principle
    of explosion_, which asserts that a contradictory hypothesis
    entails anything (even false things!). *)

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

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

(** 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.
  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": from [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 silly3' : forall (n : nat),
  (n =? 5 = true -> (S (S n)) =? 7 = true) ->
  true = (n =? 5)  ->
  true = ((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.

    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

       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 _those 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] 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' *) simpl.

(** Notice that both the goal and the induction hypothesis are
    different this time: 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 whichever
    [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 we need to be
    careful, when using induction, that we 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 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.
  - destruct m.
    + reflexivity.
    + discriminate.
  - destruct m.
    + discriminate.
    + intros. f_equal. simpl in H. apply IHn in H. apply H.
Qed.

(** [] *)

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

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

(*
    We prove this by induction on n.

    Case 1, suppose n = 0. We need to prove 0 =? m -> 0 = m.
    We split the two possible cases for m:
    When m = 0, clearly 0=0.
    When m = S m', then the assumption 0 =? S m' never holds.

    Case 2, suppose n = S n'.
    We need to prove that if n' =? m -> n' = m, then S n' =? m -> S n' = m.
    We split the two possible cases for m:
    When m = 0, the assumption S n' = 0 never holds.
    When m = S m', we need to prove S n' = S m', by functional equality,
    the goal is equal to n' = m'.
    The assumption S n' =? S m' implies n' =? m' by injectivity.
    Given this assumption and inductive hypotheses, we prove the goal.

*)

(* 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].) *)
Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n.
  induction n.
  - simpl. intros. destruct m.
    + reflexivity.
    + discriminate H.
  - simpl. intros. destruct m.
    + discriminate H.
    + f_equal. simpl in H. rewrite <- plus_n_Sm in H. rewrite <- plus_n_Sm in H.
      injection H. intros. apply IHn. apply H0.
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.
        (* Stuck again 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.
  generalize dependent l.
  induction n.
  - (* we show that when n = 0, l = [] *)
    intros. destruct l.
    + reflexivity.
    + simpl in H. discriminate H.
  - (* we show that when n = S n', l = x :: l', and the theorem holds *)
    intros. destruct l.
    + simpl in H. discriminate H.
    + simpl in H. injection H as H. simpl. apply IHn. 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 mult_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, some 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.

(** However, 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.
  - simpl. intros. injection H. intros. rewrite <- H0. rewrite <- H1.
    reflexivity.
  - intros. destruct x. destruct l1, l2.
    + (* l1 = [], l2 = [] *) simpl in H. destruct (split l). discriminate H.
    + (* l1 = [], l2 = (_::_) *) simpl in H. destruct (split l). discriminate H.
    + (* l1 = (_::_), l2 = [] *) simpl in H. destruct (split l). discriminate H.
    + (* l1 = (x0::l1), l2 = (x1::l2) *) simpl.
      simpl in H. destruct (split l). injection H. intros.
      rewrite IHl. rewrite H1. rewrite H3. reflexivity.
      rewrite H0. rewrite H2. reflexivity.
Qed.
(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional: So far,
    we've chosen to include it most of the time, just for the sake of
    documentation.

    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 ->
     oddb 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 occurences 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 ->
     oddb 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.
  destruct (f true) eqn:ft; destruct (f false) eqn:ff; destruct b;
    repeat (try rewrite ft; try rewrite ff); reflexivity.
Qed.

(* above is equivalent to enumerating all cases below *)
Theorem bool_fn_applied_thrice' :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros.
  destruct (f true) eqn:ft; destruct (f false) eqn:ff; destruct b.
  - rewrite ft. rewrite ft. rewrite ft. reflexivity.
  - rewrite ff. rewrite ft. rewrite ft. reflexivity.
  - rewrite ft. rewrite ft. rewrite ft. reflexivity.
  - rewrite ff. rewrite ff. rewrite ff. reflexivity.
  - rewrite ft. rewrite ff. rewrite ft. reflexivity.
  - rewrite ff. rewrite ft. rewrite ff. reflexivity.
  - rewrite ft. rewrite ff. rewrite ff. reflexivity.
  - rewrite ff. rewrite ff. rewrite ff. 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]: 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.
  - intro. destruct m.
    + reflexivity.
    + reflexivity.
  - intro. destruct m.
    + reflexivity.
    + simpl. rewrite IHn. reflexivity.
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: *)
   (* skipping this one
    [] *)

(** **** Exercise: 3 stars, standard, optional (eqb_trans)  *)
Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  intros.
  apply eqb_true in H.
  apply eqb_true in H0.
  rewrite H. rewrite <- H0.
  rewrite <- eqb_refl. reflexivity.
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?) *)

Definition split_combine_statement : Prop :=
  forall X (l1 l2 : list X), length l1 = length l2 -> split (combine l1 l2) = (l1, l2).
  (* ("[: Prop]" means that we are giving a name to a
     logical proposition here.) *)

Theorem split_combine : split_combine_statement.
Proof.
  unfold split_combine_statement.
  intros X l1 l2 Hl.
  generalize dependent l2.
  induction l1 as [|x1 l1'].
  - simpl. intros. f_equal. destruct l2. reflexivity. discriminate Hl.
  - simpl. destruct l2 as [|x2 l2']; intros.
    + simpl in Hl. discriminate Hl.
    + simpl in Hl. injection Hl as Hl. apply IHl1' in Hl.
      simpl split. rewrite Hl. 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. *)

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.
  - intros. simpl in H. discriminate H.
  - simpl. intros. destruct (test x0) eqn:testx0.
    + injection H. intros. rewrite <- H1. rewrite testx0. reflexivity.
    + apply IHl with (lf:=lf). rewrite H. reflexivity.
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 oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [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 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].

    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
  | (x::l') => if test x
             then forallb test l'
             else false
  end.

Example test_forallb_1 : forallb oddb [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 evenb [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
  | (x::l') => if test x
             then true
             else existsb test l'
  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 oddb [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.

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

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

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' oddb [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.

Example test_existsb'_4 : existsb' evenb [] = false.
Proof. reflexivity. Qed.

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

(* 2020-09-09 20:51 *)

author: shouya

repo: thinking-dumps

save_path: github-repos/coq/shouya-thinking-dumps


text:
(precise)admin@localhost:~/Downloads/coq_ide/logic$ coqtop
Welcome to Coq 8.3pl4 (April 2012)

Coq < Section Connectives.

Coq < Variables S T R : Prop.
S is assumed
T is assumed
R is assumed

Coq < Goal ((S -> T) /\ (T -> R) /\ ~R) -> ~S.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  ============================
   (S -> T) /\ (T -> R) /\ ~ R -> ~ S

Unnamed_thm < intros.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : (S -> T) /\ (T -> R) /\ ~ R
  ============================
   ~ S

Unnamed_thm < elim H.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : (S -> T) /\ (T -> R) /\ ~ R
  ============================
   (S -> T) -> (T -> R) /\ ~ R -> ~ S

Unnamed_thm < intro.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : (S -> T) /\ (T -> R) /\ ~ R
  H0 : S -> T
  ============================
   (T -> R) /\ ~ R -> ~ S

Unnamed_thm < intro.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : (S -> T) /\ (T -> R) /\ ~ R
  H0 : S -> T
  H1 : (T -> R) /\ ~ R
  ============================
   ~ S

Unnamed_thm < auto.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : (S -> T) /\ (T -> R) /\ ~ R
  H0 : S -> T
  H1 : (T -> R) /\ ~ R
  ============================
   ~ S

Unnamed_thm < destruct H.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : S -> T
  H2 : (T -> R) /\ ~ R
  H0 : S -> T
  H1 : (T -> R) /\ ~ R
  ============================
   ~ S

Unnamed_thm < auto.
1 subgoal

  S : Prop
  T : Prop
  R : Prop
  H : S -> T
  H2 : (T -> R) /\ ~ R
  H0 : S -> T
  H1 : (T -> R) /\ ~ R
  ============================
   ~ S

Unnamed_thm < tauto.
Proof completed.

Unnamed_thm < Qed.
intros.
elim H.
intro.
intro.
auto.
destruct H.
auto.
tauto.

Unnamed_thm is defined

Coq <

author: billwestfall


text:
Require Import VST.floyd.base.
Require Import VST.floyd.PTops.
Require Import VST.floyd.QPcomposite.
Import compcert.lib.Maps.

Fixpoint filter_options {A B} (f: A -> option B) (al: list A) : list B :=
 match al with
 | nil => nil
 | a::al' => match f a with Some b => b :: filter_options f al' | None => filter_options f al' end
 end.

Definition is_builtin {F} (ix: ident * globdef (fundef F) type) : option (ident * QP.builtin) :=
 match ix with
 | (i, Gfun (External ef params ty cc)) =>
    match ef with
    | EF_builtin _ _ => Some (i, QP.mk_builtin ef params ty cc)
    | EF_runtime _ _ => Some (i, QP.mk_builtin ef params ty cc)
    | _ => None
    end
 | _ => None
 end.

Definition isNone {A} (x: option A) := match x with None => true | _ => false end.

Definition not_builtin {F} (ix: ident * globdef (fundef F) type) : bool := isNone (is_builtin ix).

Definition of_builtin {F} (ix: ident * QP.builtin) : ident * globdef (fundef F) type :=
 match ix with
 | (i, QP.mk_builtin ef params ty cc) => (i, Gfun (External ef params ty cc))
 end.

Definition program_of_QPprogram {F} (p: QP.program F)
   : Errors.res (Ctypes.program F) :=
 let defs := map of_builtin p.(QP.prog_builtins) ++ PTree.elements p.(QP.prog_defs) in
 let public := p.(QP.prog_public) in
 let main := p.(QP.prog_main) in
 let types := map compdef_of_compenv_element
                             (sort_rank (PTree.elements (p.(QP.prog_comp_env))) nil) in
 make_program types defs public main.

Definition QPprogram_of_program {F} (p: Ctypes.program F)
      (ha: PTree.t Z) (la: PTree.t legal_alignas_obs)   : QP.program F :=
 {| QP.prog_builtins :=  filter_options is_builtin p.(prog_defs);
   QP.prog_defs := PTree_Properties.of_list (filter not_builtin p.(prog_defs));
   QP.prog_public := p.(prog_public);
   QP.prog_main := p.(prog_main);
   QP.prog_comp_env := QPcomposite_env_of_composite_env
                                        p.(prog_comp_env) ha la
 |}.

Import ListNotations.

Definition signature_of_fundef (fd: Ctypes.fundef Clight.function):signature :=
match fd with
    Internal f => {| sig_args := map typ_of_type (map snd (Clight.fn_params f));
                     sig_res := rettype_of_type (Clight.fn_return f);
                     sig_cc := Clight.fn_callconv f |}
  | External ef tys rt cc => signature_of_type tys rt cc
 end.

Lemma eqb_typelist_prop: forall t1 t2, eqb_typelist t1 t2 = true -> t1=t2.
Proof.
clear.
induction t1; destruct t2; simpl; intros; auto; try discriminate.
destruct (eqb_type t t0) eqn:?H; try discriminate.
apply eqb_type_true in H0.
f_equal; auto.
Qed.

Definition eqb_typ (t1 t2 : typ) : bool :=
 match t1, t2 with
 | AST.Tint, AST.Tint => true
 | AST.Tfloat, AST.Tfloat => true
 | AST.Tlong, AST.Tlong => true
 | AST.Tsingle, AST.Tsingle => true
 | AST.Tany32, AST.Tany32 => true
 | AST.Tany64, AST.Tany64 => true
 | _, _ => false
 end.

Lemma eqb_typ_refl: forall c, eqb_typ c c = true.
Proof.
destruct c; simpl; try reflexivity.
Qed.

Lemma eqb_typ_prop: forall s1 s2, eqb_typ s1 s2 = true -> s1=s2.
Proof.
destruct s1, s2; simpl; intros; inv H; auto.
Qed.

Lemma eqb_typelist_refl: forall c, eqb_typelist c c = true.
Proof.
induction c; simpl; auto.
rewrite eqb_type_refl, IHc; auto.
Qed.

Definition eqb_rettype (t1 t2 : rettype) : bool :=
 match t1, t2 with
 | AST.Tret a1, AST.Tret a2 => eqb_typ a1 a2
 | AST.Tint8signed, AST.Tint8signed => true
 | AST.Tint8unsigned, AST.Tint8unsigned => true
 | AST.Tint16signed, AST.Tint16signed => true
 | AST.Tint16unsigned, AST.Tint16unsigned => true
 | AST.Tvoid, AST.Tvoid => true
 | _, _ => false
 end.

Lemma eqb_rettype_refl: forall c, eqb_rettype c c = true.
Proof.
destruct c; simpl; try reflexivity.
apply eqb_typ_refl.
Qed.

Lemma eqb_rettype_prop: forall s1 s2, eqb_rettype s1 s2 = true -> s1=s2.
Proof.
destruct s1, s2; simpl; intros; inv H; auto.
f_equal.
apply eqb_typ_prop in H1; auto.
Qed.

Definition eqb_signature (s1 s2: signature) : bool :=
 match s1, s2 with
 |  mksignature args1 res1 cc1, mksignature args2 res2 cc2 =>
      eqb_list eqb_typ args1 args2 && eqb_rettype res1 res2 && eqb_calling_convention cc1 cc2
 end.

Lemma eqb_list_refl: forall {A} (f: A -> A -> bool),
  (forall a, f a a = true) ->
  forall al, eqb_list f al al = true.
Proof.
induction al; simpl; auto.
rewrite H, IHal; auto.
Qed.

Lemma eqb_list_prop:  forall {A} (f: A -> A -> bool),
  (forall a b, f a b = true -> a=b) ->
  forall al bl, eqb_list f al bl = true -> al = bl.
Proof.
induction al; destruct bl; simpl; intros; try discriminate; auto.
rewrite andb_true_iff in H0; destruct H0;
f_equal; auto.
Qed.

Lemma eqb_signature_refl: forall c, eqb_signature c c = true.
Proof.
destruct c; simpl; try reflexivity.
rewrite eqb_list_refl.
rewrite eqb_rettype_refl.
rewrite eqb_calling_convention_refl.
auto.
apply eqb_typ_refl.
Qed.

Lemma eqb_signature_prop: forall s1 s2, eqb_signature s1 s2 = true -> s1=s2.
Proof.
intros.
destruct s1, s2; simpl in *.
rewrite !andb_true_iff in H; destruct H as [[? ?] ?].
assert (sig_res = sig_res0). {
 destruct sig_res, sig_res0; inv H0; auto.
 destruct t,t0; inv H3; auto.
}
assert (sig_args = sig_args0). {
 clear - H.
 revert sig_args0 H; induction sig_args; destruct sig_args0; simpl; intros; inv H; auto.
  rewrite andb_true_iff in H1; destruct H1; f_equal; auto.
  destruct a,t; inv H; auto.
}
apply eqb_calling_convention_prop in H1.
subst; auto.
Qed.

Definition eqb_memory_chunk (c1 c2: memory_chunk) : bool :=
 match c1, c2 with
 | Mint8signed, Mint8signed => true
 | Mint8unsigned, Mint8unsigned => true
 | Mint16signed, Mint16signed => true
 | Mint16unsigned, Mint16unsigned => true
 | Mint32, Mint32 => true
 | Mint64, Mint64 => true
 | Mfloat32, Mfloat32 => true
 | Mfloat64, Mfloat64 => true
 | Many32, Many32 => true
 | Many64, Many64 => true
 | _, _ => false
 end.

Lemma eqb_memory_chunk_refl: forall c, eqb_memory_chunk c c = true.
Proof.
destruct c; reflexivity.
Qed.

Lemma eqb_memory_chunk_prop: forall c1 c2, eqb_memory_chunk c1 c2 = true -> c1=c2.
Proof.
intros.
destruct c1,c2; inv H; reflexivity.
Qed.

Definition eqb_external_function (ef1 ef2: external_function) : bool :=
 match ef1, ef2 with
 | EF_external s1 sg1, EF_external s2 sg2 => String.eqb s1 s2 && eqb_signature sg1 sg2
 | EF_builtin s1 sg1, EF_builtin s2 sg2  => String.eqb s1 s2 && eqb_signature sg1 sg2
 | EF_runtime  s1 sg1, EF_runtime s2 sg2  => String.eqb s1 s2 && eqb_signature sg1 sg2
 | EF_vload ch1, EF_vload ch2 => eqb_memory_chunk ch1 ch2
 | EF_vstore ch1, EF_vstore ch2 => eqb_memory_chunk ch1 ch2
 | EF_malloc, EF_malloc => true
 | EF_free, EF_free => true
 | EF_memcpy i1 j1, EF_memcpy i2 j2 => Z.eqb i1 i2 && Z.eqb j1 j2
 | EF_annot p1 s1 t1, EF_annot p2 s2 t2 => Pos.eqb p1 p2 && String.eqb s1 s2 && eqb_list eqb_typ t1 t2
 | EF_annot_val p1 s1 t1, EF_annot_val p2 s2 t2 => Pos.eqb p1 p2 && String.eqb s1 s2 && eqb_typ t1 t2
 | EF_inline_asm s1 sg1 al1, EF_inline_asm s2 sg2 al2 =>
            String.eqb s1 s2 && eqb_signature sg1 sg2 && eqb_list String.eqb al1 al2
 | EF_debug p1 i1 t1, EF_debug p2 i2 t2 =>
            Pos.eqb p1 p2 && eqb_ident i1 i2 &&  eqb_list eqb_typ t1 t2
 | _ , _ => false
 end.

Lemma eqb_external_function_refl: forall c, eqb_external_function c c = true.
Proof.
destruct c; simpl; try reflexivity;
rewrite ?String.eqb_refl, ?eqb_signature_refl, ?eqb_memory_chunk_refl, ?Pos.eqb_refl, ?Z.eqb_refl,
  ?eqb_typ_refl, ?eqb_list_refl; auto.
apply eqb_typ_refl.
apply String.eqb_refl.
apply eqb_typ_refl.
Qed.

Lemma eqb_external_function_prop: forall c1 c2, eqb_external_function c1 c2 = true -> c1=c2.
Proof.
intros.
destruct c1,c2; inv H; try reflexivity;
rewrite ?andb_true_iff in *;
repeat match goal with H: _ /\ _ |- _ => destruct H end;
f_equal;
try (apply -> String.eqb_eq; auto);
try (apply eqb_signature_prop; auto);
try (apply eqb_memory_chunk_prop; auto);
try (apply -> Z.eqb_eq; auto);
try (apply -> Pos.eqb_eq; auto).
apply eqb_list_prop in H0; auto; apply eqb_typ_prop.
apply eqb_typ_prop; auto.
apply eqb_list_prop in H0; auto.
intros. apply String.eqb_eq; auto.
apply eqb_list_prop in H0; auto; apply eqb_typ_prop.
Qed.

Definition eqb_unop (a1 a2 : Cop.unary_operation) : bool :=
 match a1, a2 with
 | Cop.Onotbool, Cop.Onotbool => true
 | Cop.Onotint, Cop.Onotint => true
 | Cop.Oneg, Cop.Oneg => true
 | Cop.Oabsfloat, Cop.Oabsfloat => true
 | _, _ => false
 end.

Definition eqb_binop (a1 a2 : Cop.binary_operation) : bool :=
 match a1, a2 with
 | Cop.Oadd, Cop.Oadd => true
 | Cop.Osub, Cop.Osub => true
 | Cop.Omul, Cop.Omul => true
 | Cop.Odiv, Cop.Odiv => true
 | Cop.Omod, Cop.Omod => true
 | Cop.Oand, Cop.Oand => true
 | Cop.Oor, Cop.Oor => true
 | Cop.Oxor, Cop.Oxor => true
 | Cop.Oshl, Cop.Oshl => true
 | Cop.Oshr, Cop.Oshr => true
 | Cop.Oeq, Cop.Oeq => true
 | Cop.One, Cop.One => true
 | Cop.Olt, Cop.Olt => true
 | Cop.Ogt, Cop.Ogt => true
 | Cop.Ole, Cop.Ole => true
 | Cop.Oge, Cop.Oge => true
 | _, _ => false
 end.

Fixpoint eqb_expr (e1 e2 : expr) : bool :=
 match e1, e2 with
 | Econst_int i1 t1, Econst_int i2 t2 =>
    andb (Int.eq i1 i2) (eqb_type t1 t2)
| Econst_float f1 t1, Econst_float f2 t2 =>
    andb (Int64.eq (Float.to_bits f1) (Float.to_bits f2)) (eqb_type t1 t2)
| Econst_single f1 t1, Econst_single f2 t2 =>
    andb (Int.eq (Float32.to_bits f1) (Float32.to_bits f2)) (eqb_type t1 t2)
| Econst_long i1 t1, Econst_long i2 t2 =>
    andb (Int64.eq i1 i2) (eqb_type t1 t2)
| Evar i1 t1, Evar i2 t2 =>
    andb (eqb_ident i1 i2) (eqb_type t1 t2)
| Etempvar i1 t1, Etempvar i2 t2 =>
    andb (eqb_ident i1 i2) (eqb_type t1 t2)
| Ederef a1 t1, Ederef a2 t2 =>
    andb (eqb_expr a1 a2) (eqb_type t1 t2)
| Eaddrof a1 t1, Eaddrof a2 t2 =>
    andb (eqb_expr a1 a2) (eqb_type t1 t2)
| Eunop op1 a1 t1, Eunop op2 a2 t2 =>
    andb (eqb_unop op1 op2) (andb (eqb_expr a1 a2) (eqb_type t1 t2))
| Ebinop op1 a1 b1 t1, Ebinop op2 a2 b2 t2 =>
    andb (eqb_binop op1 op2) (andb (eqb_expr a1 a2)
     (andb (eqb_expr b1 b2) (eqb_type t1 t2)) )
| Ecast a1 t1, Ecast a2 t2 =>
    andb (eqb_expr a1 a2) (eqb_type t1 t2)
| Efield a1 i1 t1, Efield a2 i2 t2 =>
    andb (eqb_expr a1 a2)
     (andb (eqb_ident i1 i2) (eqb_type t1 t2))
| Esizeof a1 t1, Esizeof a2 t2 =>
    andb (eqb_type a1 a2) (eqb_type t1 t2)
| Ealignof a1 t1, Ealignof a2 t2 =>
    andb (eqb_type a1 a2) (eqb_type t1 t2)
| _, _ => false
end.

Lemma eqb_expr_prop: forall e1 e2, eqb_expr e1 e2 = true -> e1=e2.
Proof.
induction e1; destruct e2; intros; inv H; auto;
rewrite !andb_true_iff in H1; decompose [and] H1; clear H1;
f_equal; auto;
try (apply Int.same_if_eq; auto);
try (apply Int64.same_if_eq; auto);
try (apply eqb_type_true; auto);
try (apply Peqb_true_eq; auto).
apply Int64.same_if_eq in H.
rewrite <- (Float.of_to_bits f), <- (Float.of_to_bits f0); congruence.
apply Int.same_if_eq in H.
rewrite <- (Float32.of_to_bits f), <- (Float32.of_to_bits f0); congruence.
destruct u,u0; inv H; auto.
destruct b,b0; inv H; auto.
Qed.

Fixpoint eqb_statement (s1 s2: statement ) : bool :=
match s1, s2 with
| Sskip, Sskip => true
| Sassign a1 b1, Sassign a2 b2 =>
       andb (eqb_expr a1 a2) (eqb_expr b1 b2)
| Sset i1 a1, Sset i2 a2 =>
       andb (eqb_ident i1 i2) (eqb_expr a1 a2)
| Scall i1 a1 b1, Scall i2 a2 b2 =>
   andb (eqb_option eqb_ident i1 i2)
    (andb (eqb_expr a1 a2) (eqb_list eqb_expr b1 b2))
| Sbuiltin i1 f1 t1 b1, Sbuiltin i2 f2 t2 b2 =>
  andb (eqb_option eqb_ident i1 i2)
   (andb (eqb_external_function f1 f2)
    (andb (eqb_typelist t1 t2) (eqb_list eqb_expr b1 b2)))
| Ssequence a1 b1, Ssequence a2 b2 =>
    andb (eqb_statement a1 a2) (eqb_statement b1 b2)
| Sifthenelse e1 a1 b1, Sifthenelse e2 a2 b2 =>
   andb (eqb_expr e1 e2)
   (andb (eqb_statement a1 a2) (eqb_statement b1 b2))
| Sloop a1 b1, Sloop a2 b2 =>
    andb (eqb_statement a1 a2) (eqb_statement b1 b2)
| Sbreak, Sbreak => true
| Scontinue, Scontinue => true
| Sreturn a1, Sreturn a2 =>
         (eqb_option eqb_expr a1 a2)
| Sswitch e1 s1, Sswitch e2 s2 =>
  andb (eqb_expr e1 e2) (eqb_labeled_statements s1 s2)
| Slabel i1 s1, Slabel i2 s2  =>
       andb (eqb_ident i1 i2) (eqb_statement s1 s2)
| Sgoto i1, Sgoto i2 =>
       eqb_ident i1 i2
| _, _ => false
 end
with eqb_labeled_statements (s1 s2: labeled_statements) :=
match s1, s2 with
| LSnil, LSnil => true
| LScons i1 a1 b1, LScons i2 a2 b2 =>
  andb (eqb_option Z.eqb i1 i2)
    (andb (eqb_statement a1 a2) (eqb_labeled_statements b1 b2))
| _, _ => false
end.

Lemma eqb_statement_prop: forall s1 s2, eqb_statement s1 s2 = true -> s1=s2
with eqb_labeled_statements_prop: forall s1 s2,
  eqb_labeled_statements s1 s2 = true -> s1=s2.
Proof.
- clear eqb_statement_prop.
induction s1; destruct s2; intros; inv H; auto;
rewrite ?andb_true_iff in H1; decompose [and] H1;
f_equal; auto;
try solve[apply Int.same_if_eq; auto];
try solve[apply Int64.same_if_eq; auto];
try solve[apply eqb_type_true; auto];
try solve[apply Peqb_true_eq; auto];
try solve[apply eqb_expr_prop; auto];
try solve[destruct o,o0; try discriminate; auto; f_equal; simpl in H;
       apply eqb_ident_spec; auto];
try solve[apply (eqb_list_prop _ eqb_expr_prop); auto];
try solve[apply eqb_external_function_prop; auto];
try solve [apply eqb_typelist_prop; auto].
destruct o,o0; try discriminate; auto; f_equal; simpl in H1.
apply eqb_expr_prop; auto.
- clear eqb_labeled_statements_prop.
induction s1; destruct s2; intros; inv H; auto.
rewrite ?andb_true_iff in H1; decompose [and] H1;
f_equal; auto.
destruct o,o0; try discriminate; auto; f_equal; simpl in H.
apply Z.eqb_eq; auto.
Qed.

Lemma eqb_ident_refl: forall i, eqb_ident i i = true.
Proof.
intros.
apply Pos.eqb_eq; auto.
Qed.

Lemma eqb_expr_refl: forall e, eqb_expr e e = true.
Proof.
induction e; simpl; auto;
rewrite ?Int.eq_true, ?Int64.eq_true, ?eqb_type_refl, ?eqb_ident_refl,
  ?andb_true_r; auto.
 rewrite IHe. destruct u; reflexivity.
 rewrite IHe1, IHe2; destruct b; reflexivity.
Qed.

Lemma eqb_statement_refl: forall s, eqb_statement s s = true
with eqb_labeled_statements_refl: forall s, eqb_labeled_statements s s = true.
Proof.
- clear eqb_statement_refl.
induction s; simpl; auto;
rewrite ?Int.eq_true, ?Int64.eq_true, ?eqb_type_refl, ?eqb_ident_refl,
  ?eqb_expr_refl,  ?andb_true_r; auto;
 rewrite ?eqb_list_refl by apply eqb_expr_refl;
 rewrite ?eqb_external_function_refl, ?eqb_typelist_refl,
 ?IHs, ?IHs1, ?IHs2; auto.
 destruct o; auto; simpl; rewrite eqb_ident_refl; auto.
 destruct o; auto; simpl; rewrite eqb_ident_refl; auto.
 destruct o; auto; simpl; rewrite eqb_expr_refl; auto.
 simpl; auto.
- clear eqb_labeled_statements_refl.
induction s; simpl; auto.
 rewrite eqb_statement_refl, IHs.
 destruct o; auto; simpl.
 rewrite andb_true_r.
 apply Z.eqb_eq. auto.
Qed.

Definition eqb_var (a b : ident * type) : bool :=
 eqb_ident (fst a) (fst b) && eqb_type (snd a) (snd b).

Lemma eqb_var_spec
     : forall a b : ident*type, eqb_var a b = true <-> a = b.
Proof.
intros.
unfold eqb_var.
rewrite andb_true_iff.
rewrite (eqb_ident_spec (fst a) (fst b)).
rewrite eqb_type_spec.
destruct a,b; simpl.
split; intros. destruct H; congruence. split; congruence.
Qed.

Definition function_eq (f1 f2: Clight.function) : bool :=
eqb_type f1.(Clight.fn_return) f2.(Clight.fn_return) &&
eqb_calling_convention f1.(Clight.fn_callconv) f2.(Clight.fn_callconv) &&
eqb_list eqb_var f1.(Clight.fn_params) f2.(Clight.fn_params) &&
eqb_list eqb_var f1.(Clight.fn_vars) f2.(Clight.fn_vars) &&
eqb_list eqb_var f1.(Clight.fn_temps) f2.(Clight.fn_temps) &&
eqb_statement f1.(Clight.fn_body) f2.(Clight.fn_body).

Definition fundef_eq  (fd1 fd2: fundef Clight.function) : bool :=
match fd1, fd2 with
| Internal f1, Internal f2 => function_eq f1 f2
| External ef1 params1 res1 cc1, External ef2 params2 res2 cc2 =>
        eqb_external_function ef1 ef2 &&
        eqb_typelist params1 params2 &&
        eqb_type res1 res2 &&
        eqb_calling_convention cc1 cc2
 | _, _ => false
end.

Lemma function_eq_prop: forall f1 f2, function_eq f1 f2 = true -> f1=f2.
Proof.
intros.
unfold function_eq in H.
repeat (revert H; match goal with |- ?A && _ = true -> _ => destruct A eqn:?H; simpl; intro; [ | discriminate] end).
apply eqb_type_true in H.
apply eqb_calling_convention_prop in H4.
apply eqb_statement_prop in H0.
apply (eqb_list_spec _ eqb_var_spec) in H1.
apply (eqb_list_spec _ eqb_var_spec) in H2.
apply (eqb_list_spec _ eqb_var_spec) in H3.
destruct f1,f2; simpl in *; congruence.
Qed.

Lemma fundef_eq_prop: forall fd1 fd2, fundef_eq fd1 fd2 = true -> fd1 = fd2.
Proof.
intros.
destruct fd1, fd2; inv H.
- apply function_eq_prop in H1; congruence.
-
rewrite !andb_true_iff in H1. decompose [and] H1; clear H1.
f_equal.
apply eqb_external_function_prop; auto.
apply eqb_typelist_prop; auto.
apply eqb_type_true; auto.
apply eqb_calling_convention_prop; auto.
Qed.

Definition overlap_Gvar :=
  (* This controls whether we permit linking programs P1 and P2 that both contain
     the same Gvar *)
   false.

Definition isnil {A} (al: list A) :=
   match al with nil => true | _ => false end.

Definition merge_globvar (gv1 gv2: globvar type) : Errors.res (globvar type) :=
 match gv1, gv2 with
 |  {| gvar_info := i1; gvar_init := l1; gvar_readonly := r1; gvar_volatile := v1 |},
    {| gvar_info := i2; gvar_init := l2; gvar_readonly := r2; gvar_volatile := v2 |} =>
   if (overlap_Gvar &&
      (eqb_type i1 i2 &&
      bool_eq r1 r2 &&
      bool_eq v1 v2))%bool
   then if isnil l1
           then Errors.OK gv2
           else if isnil l2 then Errors.OK gv1
           else Errors.Error [Errors.MSG "Gvars both initialized"]
   else Errors.Error [Errors.MSG "Gvar type/readonly/volatile clash"]
 end.

Definition merge_globdef (g1 g2: globdef (fundef Clight.function) type) :=
 match g1, g2 with
 | Gfun (External ef1 params1 res1 cc1),
   Gfun (External ef2 params2 res2 cc2) =>
     if fundef_eq (External ef1 params1 res1 cc1)
                        (External ef2 params2 res2 cc2)
     then Errors.OK g1
     else Errors.Error [Errors.MSG "External functions don't match"]
 | Gfun (External e t t0 c), Gfun (Internal f2) =>
     if eqb_signature (signature_of_fundef (External e t t0 c)) (signature_of_fundef (Internal f2))
     then Errors.OK g2
     else Errors.Error [Errors.MSG "function signatures don't match"]
 | Gfun (Internal f1), Gfun (External e t t0 c) =>
     if eqb_signature (signature_of_fundef (Internal f1)) (signature_of_fundef (External e t t0 c))
     then Errors.OK g1
     else Errors.Error [Errors.MSG "function signatures don't match"]
 | Gfun (Internal f), Gfun (Internal g) =>
      if function_eq f g
      then Errors.OK g1
      else Errors.Error [Errors.MSG "internal function clash"]
 | Gvar gv1, Gvar gv2 =>
    Errors.bind (merge_globvar gv1 gv2) (fun gv => Errors.OK (Gvar gv))
  | _, _ => Errors.Error [Errors.MSG "Gvar versus Gfun"]
 end.

Definition eqb_QPbuiltin (a b: QP.builtin) : bool :=
 match a, b with
 | QP.mk_builtin ef1 params1 ty1 cc1, QP.mk_builtin ef2 params2 ty2 cc2 =>
     extspec.extfunct_eqdec ef1 ef2 && eqb_typelist params1 params2 && eqb_type ty1 ty2
       && eqb_calling_convention cc1 cc2
 end.

Lemma eqb_QPbuiltin_prop: forall a b , eqb_QPbuiltin a b = true -> a=b.
Proof.
destruct a,b; simpl; intros.
rewrite !andb_true_iff in H.
destruct H as [[[??] ?] ?].
destruct (extspec.extfunct_eqdec e e0); inv H.
apply eqb_typelist_prop in H0.
apply eqb_type_true in H1.
apply eqb_calling_convention_prop in H2.
subst; auto.
Qed.

Fixpoint eqb_builtins (al bl: list (ident * QP.builtin)) : bool :=
match al, bl with
| nil, nil => true
| (i,a)::al', (j,b)::bl' => eqb_ident i j && eqb_QPbuiltin a b && eqb_builtins al' bl'
| _, _ => false
end.

Lemma eqb_builtins_prop: forall al bl, eqb_builtins al bl = true -> al=bl.
Proof.
induction al as [|[??]]; destruct bl as [|[??]]; simpl; intros; auto; try discriminate.
rewrite !andb_true_iff in H.
destruct H as [[? ?] ?].
rewrite (proj1 (eqb_ident_spec _ _) H).
apply eqb_QPbuiltin_prop in H0.
subst; f_equal; auto.
Qed.

Lemma eqb_builtins_refl: forall a, eqb_builtins a a = true.
Proof.
induction a as [|[i ?]]; simpl; auto.
rewrite (proj2 (eqb_ident_spec i i) (eq_refl _)).
rewrite IHa; clear.
rewrite andb_true_r. simpl.
destruct b.
simpl.
destruct (extspec.extfunct_eqdec e e); try congruence.
simpl; clear.
rewrite eqb_typelist_refl, eqb_type_refl, eqb_calling_convention_refl.
reflexivity.
Qed.

Definition merge_builtins (al bl: list (ident * QP.builtin)) :
   Errors.res (list (ident * QP.builtin)) :=
 if eqb_builtins al bl then Errors.OK al else Errors.Error [Errors.MSG "builtins differ"].

Definition QPlink_progs (p1 p2: QP.program Clight.function) : Errors.res (QP.program Clight.function) :=
 Errors.bind (merge_builtins p1.(QP.prog_builtins) p2.(QP.prog_builtins)) (fun builtins =>
 Errors.bind (merge_PTrees merge_globdef (p1.(QP.prog_defs)) p2.(QP.prog_defs)) (fun defs =>
 Errors.bind (merge_consistent_PTrees QPcomposite_eq
                p1.(QP.prog_comp_env) p2.(QP.prog_comp_env)) (fun ce =>
    if eqb_ident p1.(QP.prog_main) p2.(QP.prog_main) then
    Errors.OK
    {| QP.prog_builtins := builtins;
       QP.prog_defs := defs;
       QP.prog_public := p1.(QP.prog_public) ++ p2.(QP.prog_public);
       QP.prog_main := p1.(QP.prog_main);
       QP.prog_comp_env := ce
     |}
   else Errors.Error [Errors.MSG "QPlink_progs disagreement on main:";
                               Errors.POS p1.(QP.prog_main);
                               Errors.POS p2.(QP.prog_main)]
  ))).

(************************ *)

Lemma linked_compspecs': forall p1 p2 p
  (OK1:  QPcompspecs_OK (QP.prog_comp_env p1))
  (OK2:  QPcompspecs_OK (QP.prog_comp_env p2))
  (Linked: QPlink_progs p1 p2 = Errors.OK p),
       QPcompspecs_OK (QP.prog_comp_env p)
   /\ PTree_sub (QP.prog_comp_env p1) (QP.prog_comp_env p)
   /\ PTree_sub (QP.prog_comp_env p2) (QP.prog_comp_env p).
Proof.
intros.
unfold QPlink_progs in Linked.
destruct (merge_builtins (QP.prog_builtins p1)
              (QP.prog_builtins p2)); inv Linked.
destruct  (merge_PTrees merge_globdef (QP.prog_defs p1)
          (QP.prog_defs p2)); inv H0.
destruct (merge_consistent_PTrees QPcomposite_eq
          (QP.prog_comp_env p1) (QP.prog_comp_env p2)) eqn:?H; inv H1.
destruct (eqb_ident (QP.prog_main p1) (QP.prog_main p2)); inv H2.
simpl.
split3.
apply  (merged_compspecs' _ _ OK1 OK2 _ H).
-
intros i.
apply (merge_PTrees_e i) in H.
red.
destruct ((QP.prog_comp_env p1) ! i); auto.
destruct ((QP.prog_comp_env p2) ! i); auto.
destruct H as [? [? ?]].
rewrite H0.
destruct (QPcomposite_eq c c0) eqn:?H; inv H.
apply QPcomposite_eq_e in H1; auto.
-
intros i.
apply (merge_PTrees_e i) in H.
red.
destruct ((QP.prog_comp_env p2) ! i); auto.
destruct ((QP.prog_comp_env p1) ! i); auto.
destruct H as [? [? ?]].
rewrite H0.
destruct (QPcomposite_eq c0 c) eqn:?H; inv H.
apply QPcomposite_eq_e in H1; auto.
Qed.

Definition QPglobalenv {F: Type} (p: QP.program F) :=
Genv.add_globals (Genv.empty_genv (fundef F) type (QP.prog_public p))
  (map of_builtin (QP.prog_builtins p) ++ PTree.elements (QP.prog_defs p)).

Fixpoint QPprog_funct' {F} (al: list (ident * globdef (fundef F) type)) : list (ident * fundef F) :=
 match al with
 | nil => nil
 | (i, Gfun f)::al' => (i,f) :: QPprog_funct' al'
 | _::al' => QPprog_funct' al'
end.

Definition QPprog_funct {F} p := @QPprog_funct' F (PTree.elements (QP.prog_defs p)).

Fixpoint QPprog_vars' {F} (al: list (ident * globdef (fundef F) type)) : list (ident * globvar type) :=
 match al with
 | nil => nil
 | (i, Gvar v)::al' => (i,v) :: QPprog_vars' al'
 | _::al' => QPprog_vars' al'
end.

Definition QPprog_vars (p: QP.program function) : list (ident * globvar type) :=
 QPprog_vars' (PTree.elements (QP.prog_defs p)).

Definition QPprogram_OK {F} (p: QP.program F) :=
 list_norepet (map fst (QP.prog_builtins p)
                     ++ map fst (PTree.elements (QP.prog_defs p))) /\
 QPcompspecs_OK (QP.prog_comp_env p).

Definition QPlink_progs_OK:
  forall p1 p2 p,
    QPlink_progs p1 p2 = Errors.OK p ->
    QPprogram_OK p1 ->
    QPprogram_OK p2 ->
    QPprogram_OK p.
Proof.
intros.
destruct H0, H1.
unfold QPlink_progs in H.
Errors.monadInv H.
destruct (eqb_ident (QP.prog_main p1) (QP.prog_main p2)); inv EQ3.
split.
2: apply merged_compspecs' in EQ0; auto.
simpl.
clear - EQ EQ1 H0 H1.
unfold merge_builtins in EQ.
destruct (eqb_builtins (QP.prog_builtins p1) (QP.prog_builtins p2)) eqn:?H; inv EQ.
apply eqb_builtins_prop in H.
rewrite <- H in *.
clear H.
forget (map fst (QP.prog_builtins p1)) as A.
apply list_norepet_app in H0; destruct H0 as [? [? ?]].
apply list_norepet_app in H1; destruct H1 as [? [? ?]].
apply list_norepet_app; split3; auto.
apply PTree.elements_keys_norepet.
intros i j ? ? ?; subst j.
clear - H2 H4 EQ1 H5 H6.
apply (merge_PTrees_e i) in EQ1.
specialize (H2 i i H5).
specialize (H4 i i H5).
apply PTree_In_fst_elements in H6.
destruct H6 as [g ?].
rewrite H in EQ1.
destruct ((QP.prog_defs p1) ! i) eqn:?H.
apply H2; auto.
apply PTree_In_fst_elements; eauto.
destruct ((QP.prog_defs p2) ! i) eqn:?H.
inv EQ1.
apply H4; auto.
apply PTree_In_fst_elements; eauto.
inv EQ1.
Qed.

Lemma QPfind_def_symbol:
  forall {F} p id g,
  QPprogram_OK p ->
  In (id,g) (map of_builtin (QP.prog_builtins p)) \/ (QP.prog_defs p)!id = Some g <->
 exists b, Genv.find_symbol (@QPglobalenv F p) id = Some b
   /\ Genv.find_def (@QPglobalenv F p) b = Some g.
Proof.
intros.
unfold QPglobalenv.
transitivity (In (id,g) (map of_builtin (QP.prog_builtins p) ++ PTree.elements (QP.prog_defs p))).
-
rewrite in_app.
split; (intros [?|?]; [left|right]; auto).
apply PTree.elements_correct; auto.
apply PTree.elements_complete; auto.
-
forget (QP.prog_public p) as pubs.
apply proj1 in H.
assert (list_norepet (map fst (map of_builtin (QP.prog_builtins p) ++ PTree.elements (QP.prog_defs p)))).
replace  (map fst (map of_builtin (QP.prog_builtins p) ++ PTree.elements (QP.prog_defs p)))
   with (map fst (QP.prog_builtins p) ++ map fst (PTree.elements (QP.prog_defs p))); auto.
rewrite map_app.
f_equal.
rewrite map_map.
f_equal.
extensionality x. destruct x as [i b]. destruct b; reflexivity.
clear H; rename H0 into H.
forget (map of_builtin (QP.prog_builtins p) ++ PTree.elements (QP.prog_defs p)) as al.
clear p.
unfold Genv.add_globals.
split; intro.
+
forget (Genv.empty_genv (fundef F) type pubs) as ge.
revert ge; induction al as [|[i d]]; simpl; intros.
inv H0.
inv H.
simpl in H0.
destruct H0.
*
inv H.
clear IHal.
clear - H3.
assert (exists b : block,
  Genv.find_symbol ((Genv.add_global ge (id, g))) id = Some b /\
  Genv.find_def ((Genv.add_global ge (id, g))) b = Some g). {
  eexists; split. apply PTree.gss. apply PTree.gss.
}
set (ge' := Genv.add_global ge (id, g)) in *.
change (Genv.add_global ge (id, g)) with ge'.
clearbody ge'.
revert ge' H ; induction al as [|[i d]]; simpl; intros; auto.
assert (~In id (map fst al)) by (contradict H3; right; auto).
assert (id<>i) by (contradict H3; subst; left; auto).
apply IHal; clear IHal; auto.
destruct H as [b [? ?]].
exists b.
unfold Genv.find_symbol, Genv.find_def in *; simpl in *.
rewrite PTree.gso by auto.
split; auto.
rewrite PTree.gso; auto.
intro; subst.
pose proof (Genv.genv_symb_range _ _ H).
red in H4. lia.
*
apply (IHal H4 H (Genv.add_global ge (i, d))).
+
assert (In (id,g) al \/
           exists b, Genv.find_symbol
               (Genv.empty_genv (fundef F) type pubs) id = Some b /\
               Genv.find_def (Genv.empty_genv (fundef F) type pubs) b =
       Some g).
2:{ destruct H1; auto. destruct H1 as [? [? ?]]. unfold Genv.find_symbol in H1; simpl in H1.
               rewrite PTree.gempty in H1; inv H1.
}
forget  (Genv.empty_genv (fundef F) type pubs) as ge.
revert ge H0; induction al as [|[j c]]; simpl; intros.
destruct H0 as [b [? ?]]; right; exists b; auto.
inv H.
apply IHal in H0; clear IHal; auto.
destruct H0.
left. right. auto.
destruct H as [b [? ?]].
destruct (ident_eq j id).
subst.
unfold Genv.find_def, Genv.find_symbol in *; simpl in *.
rewrite PTree.gss in H. inv H. rewrite PTree.gss in H0. inv H0; auto.
right.
unfold Genv.find_def, Genv.find_symbol in *; simpl in *.
rewrite PTree.gso in H by auto.
exists b; split; auto.
rewrite PTree.gso in H0; auto.
intro.
subst.
pose proof (Genv.genv_symb_range _ _ H).
red in H1. lia.
Qed.

Lemma QPfind_funct_ptr_exists:
forall (p: QP.program Clight.function) i f,
  QPprogram_OK p ->
(QP.prog_defs p) ! i = Some (Gfun f) ->
exists b,
 Genv.find_symbol (QPglobalenv p) i = Some b
/\ Genv.find_funct_ptr (QPglobalenv p) b = Some f.
Proof.
intros.
destruct (proj1 (QPfind_def_symbol p i (Gfun f) H) (or_intror H0))
as [b [? ?]].
exists b; split; auto.
unfold Genv.find_funct_ptr.
rewrite H2.
auto.
Qed.

Lemma QPprogram_of_program_OK:
  forall {F} (p: program F) (cs: compspecs),
  list_norepet (map fst (prog_defs p)) ->
  @cenv_cs cs = prog_comp_env p ->
  PTree_samedom (@cenv_cs cs) (@ha_env_cs cs) ->
  PTree_samedom (@cenv_cs cs) (@la_env_cs cs) ->
   QPprogram_OK (QPprogram_of_program p (@ha_env_cs cs) (@la_env_cs cs)).
Proof.
intros.
split.
-
clear - H.
apply list_norepet_app.
split3.
+
simpl.
induction (prog_defs p).
constructor.
inv H.
destruct a.
destruct g; simpl; auto.
destruct f; simpl; auto.
simpl in H2.
assert (~ In i (map fst (filter_options is_builtin l))). {
 clear - H2; contradict H2; induction l; simpl; auto.
 destruct a; simpl in *; auto. destruct g; simpl in *; auto.
 destruct f; simpl in *; auto. destruct e; simpl in *; auto.
 destruct H2; auto. destruct H2; auto.
}
destruct e; simpl; auto;
constructor; auto.
+
apply PTree.elements_keys_norepet.
+
intros i j ? ? ?; subst j.
apply PTree_In_fst_elements in H1.
destruct H1 as [g ?].
simpl in *.
apply PTree_Properties.in_of_list in H1.
apply filter_In in H1.
destruct H1.
apply list_in_map_inv in H0.
destruct H0 as [[j g'] [? ?]].
simpl in H0; subst j.
induction (prog_defs p) as [|[j ?]].
inv H1.
simpl in *.
inv H.
destruct H1.
inv H.
destruct g.
destruct f.
apply H5.
clear - H3.
induction l; simpl in *; auto.
destruct a; auto.
destruct g; auto.
simpl in *.
destruct f; auto.
destruct e; auto; destruct H3; auto; inv H; auto.
unfold not_builtin in H2.
fold (@is_builtin function (i, Gfun (External e t t0 c))) in H3.
revert H2; destruct (is_builtin _) eqn:?H; intro H2; inv H2.
apply H5.
clear - H3.
induction l; simpl in *; auto.
destruct a; auto.
destruct g; auto.
simpl in *.
destruct f; auto.
destruct e; auto; destruct H3; auto; inv H; auto.
apply H5.
clear - H3.
induction l; simpl in *; auto.
destruct a; auto.
destruct g; auto.
simpl in *.
destruct f; auto.
destruct e; auto; destruct H3; auto; inv H; auto.
destruct g0; auto.
destruct f; auto.
destruct e; auto.
simpl in H3. destruct H3; auto.
inv H0.
apply H5.
apply (in_map fst) in H. apply H.
simpl in H3. destruct H3; auto.
inv H0.
apply H5.
apply (in_map fst) in H. apply H.
-
clear H.
simpl.
rewrite <- H0.
clear - H1 H2.
apply QPcompspecs_OK_i; auto.
Qed.

Lemma QPlink_progs_globdefs: (* move this to quickprogram.v *)
 forall p1 p2 p,
  QPlink_progs p1 p2 = Errors.OK p ->
   merge_PTrees merge_globdef (QP.prog_defs p1) (QP.prog_defs p2) =
    Errors.OK (QP.prog_defs p).
Proof.
clear.
intros.
unfold QPlink_progs in H.
Errors.monadInv H.
destruct (eqb_ident (QP.prog_main p1) (QP.prog_main p2));
inv EQ3.
auto.
Qed.

Definition is_builtin' (ix: ident * QP.builtin) :=
 match ix with
 | (_, QP.mk_builtin (EF_builtin _ _)  _ _ _) => true
 | (_, QP.mk_builtin (EF_runtime _ _) _ _ _) => true
 | (_, _) => false
end.

Module Junkyard.

Fixpoint QPcomplete_type (env : QP.composite_env) (t : type) :  bool :=
  match t with
  | Tarray t' _ _ => QPcomplete_type env t'
  | Tvoid | Tfunction _ _ _ => false
  | Tstruct id _ | Tunion id _ =>
      match env ! id with
      | Some _ => true
      | None => false
      end
  | _ => true
  end.

Fixpoint QPcomplete_members (e: QP.composite_env) (m: members) :=
 match m with
 | nil => true
 | m1::m' => QPcomplete_type e (type_member m1) && QPcomplete_members e m'
 end.

Definition QPcomposite_env_complete (e: QP.composite_env) : Prop :=
  PTree_Forall (fun c => QPcomplete_members e (QP.co_members c) = true) e.

Lemma build_composite_env_helper :
 forall ce
  (H: QPcomposite_env_OK ce)
(*  (Hcomplete: QPcomposite_env_complete ce) *),
  build_composite_env
    (map compdef_of_compenv_element
       (PTree.elements ce)) =
  Errors.OK
    (composite_env_of_QPcomposite_env ce H).
Proof.
Abort.

(*
Definition program_of_QPprogram {F} (p: QP.program F)
  (H: QPcomposite_env_OK (p.(QP.prog_comp_env)))
  (H0: QPcomposite_env_complete (p.(QP.prog_comp_env)))
   : Ctypes.program F  :=
 {| prog_defs := PTree.elements p.(QP.prog_defs);
    prog_public := p.(QP.prog_public);
    prog_main := p.(QP.prog_main);
    prog_types := map compdef_of_compenv_element
                             (sort_rank (PTree.elements (p.(QP.prog_comp_env))) nil);
    prog_comp_env := composite_env_of_QPcomposite_env p.(QP.prog_comp_env) H;
    prog_comp_env_eq := 8
 |}.
*)

End Junkyard.

author: anonymous-submissions-VST


text:
(* Acc and well-founded recursion... *)
Require Import ZFwf ZFord.

Import WellFoundedRecursion2.

Definition AR x y :=
  (isOrd x /\ y = singl (singl empty)) \/
  (isOrd y /\ x ∈ y).
Lemma ssmt_not_ord :
  ~ isOrd (singl (singl empty)).
intro.
assert (empty ∈ singl (singl empty)).
 apply isOrd_trans with (singl empty); trivial.
 apply singl_intro.
 apply singl_intro.
apply singl_elim in H0.
apply empty_ax with empty.
apply eq_elim with (singl empty); auto with *.
apply singl_intro.
Qed.
Lemma wfARo o : isOrd o -> Acc AR o.
induction 1 using isOrd_ind.
constructor; intros.
destruct H2.
destruct H2.
rewrite H3 in H.
apply ssmt_not_ord in H; contradiction.
destruct H2.
auto.
Qed.
Lemma wfAR x : Acc AR x.
constructor; intros.
destruct H.
 destruct H.
 apply wfARo; trivial.
 destruct H.
 apply wfARo; trivial.
 apply isOrd_inv with x; trivial.
Qed.

Lemma not_an_ord :
  ~ exists2 f: set->set,
        (forall x, isOrd (f x)) &
        (forall x y, AR x y -> f x ∈ f y).
intros (f,fo,felt).
assert (forall o, isOrd o -> o ⊆ f o).
 intros.
 elim H using isOrd_ind; intros.
 red; intros.
 apply isOrd_plump with (f z); auto.
  apply isOrd_inv with y; trivial.

  apply felt.
  right; auto.
pose (w := singl (singl empty)).
assert (forall o, isOrd o -> o ∈ f w).
 intros.
 apply isOrd_plump with (f o); auto.
 apply felt.
 left; auto.
apply (lt_antirefl (f w)); auto.
apply H0; auto.
Qed.

(* But hopefully we cannot use WFR to build such a function...

Definition f x := WFR AR (fun F y => osup y (fun z => osucc (F z))) x .

Lemma fo x : isOrd (f x).
elim (wfAR x); intros.
unfold f.
rewrite WFR_eqn.
 apply isOrd_osup.
  admit.

  intros.
  apply isOrd_succ.
  apply H0.

 *)

author: barras

repo: cic-model

save_path: github-repos/coq/barras-cic-model


text:
Record wut : Type :=
{
  w1 : nat;
  w4 : nat;
  w11 : nat * nat;
}.

Goal wut -> False.
Proof.
  intros [a b c].
Restart.
  intros (a, b, c).
Restart.
  Fail intros (a & b & c).
Restart.

Abort.

author: wkolowski

repo: Typonomikon

save_path: github-repos/coq/wkolowski-Typonomikon


text:
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.

Derive Show for natural.

              Derive Arbitrary for natural.

              Instance Dec_Eq_natural : Dec_Eq natural.

              Proof. dec_eq. Qed.

Lemma conj25synthconj1_hyp: forall  (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus lv0 lv2) (mult lv2 (Succ lv1))) ->  (@eq natural (plus (plus lv0 lv1) (Succ (plus Zero lv2))) (plus (mult lv2 (Succ lv1)) (Succ lv1))).
Admitted.
QuickChick conj25synthconj1_hyp.

author: yalhessi

repo: lemmaranker

save_path: github-repos/coq/yalhessi-lemmaranker