(* Copyright (c) 2008-2012, 2015, Adam Chlipala
 *
 * This work is licensed under a
 * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
 * Unported License.
 * The license text is available at:
 *   http://creativecommons.org/licenses/by-nc-nd/3.0/
 *)

(* begin hide *)
Require Import List.

Require Import Cpdt.CpdtTactics.

Set Implicit Arguments.
Set Asymmetric Patterns.

(* Extra definitions to get coqdoc to choose the right fonts. *)

(* begin thide *)
Inductive unit := tt.
Inductive Empty_set := .
Inductive bool := true | false.
Inductive sum := .
Inductive prod := .
Inductive and := conj.
Inductive or := or_introl | or_intror.
Inductive ex := ex_intro.
Inductive eq := eq_refl.
Reset unit.
(* end thide *)
(* end hide *)

(** %\chapter{Inductive Predicates}% *)

(** The so-called %\index{Curry-Howard correspondence}``%#"#Curry-Howard correspondence#"#%''~\cite{Curry,Howard}% states a formal connection between functional programs and mathematical proofs.  In the last chapter, we snuck in a first introduction to this subject in Coq.  Witness the close similarity between the types [unit] and [True] from the standard library: *)

Print unit.
(** %\vspace{-.15in}%[[
  Inductive unit : Set :=  tt : unit
]]
*)

Print True.
(** %\vspace{-.15in}%[[
  Inductive True : Prop :=  I : True
  ]]

Recall that [unit] is the type with only one value, and [True] is the proposition that always holds.  Despite this superficial difference between the two concepts, in both cases we can use the same inductive definition mechanism.  The connection goes further than this.  We see that we arrive at the definition of [True] by replacing [unit] by [True], [tt] by [I], and [Set] by [Prop].  The first two of these differences are superficial changes of names, while the third difference is the crucial one for separating programs from proofs.  A term [T] of type [Set] is a type of programs, and a term of type [T] is a program.  A term [T] of type [Prop] is a logical proposition, and its proofs are of type [T].  Chapter 12 goes into more detail about the theoretical differences between [Prop] and [Set].  For now, we will simply follow common intuitions about what a proof is.

The type [unit] has one value, [tt].  The type [True] has one proof, [I].  Why distinguish between these two types?  Many people who have read about Curry-Howard in an abstract context but who have not put it to use in proof engineering answer that the two types in fact _should not_ be distinguished.  There is a certain aesthetic appeal to this point of view, but I want to argue that it is best to treat Curry-Howard very loosely in practical proving.  There are Coq-specific reasons for preferring the distinction, involving efficient compilation and avoidance of paradoxes in the presence of classical math, but I will argue that there is a more general principle that should lead us to avoid conflating programming and proving.

The essence of the argument is roughly this: to an engineer, not all functions of type [A -> B] are created equal, but all proofs of a proposition [P -> Q] are.  This idea is known as%\index{proof irrelevance}% _proof irrelevance_, and its formalizations in logics prevent us from distinguishing between alternate proofs of the same proposition.  Proof irrelevance is compatible with, but not derivable in, Gallina.  Apart from this theoretical concern, I will argue that it is most effective to do engineering with Coq by employing different techniques for programs versus proofs.  Most of this book is organized around that distinction, describing how to program, by applying standard functional programming techniques in the presence of dependent types; and how to prove, by writing custom Ltac decision procedures.

With that perspective in mind, this chapter is sort of a mirror image of the last chapter, introducing how to define predicates with inductive definitions.  We will point out similarities in places, but much of the effective Coq user's bag of tricks is disjoint for predicates versus "datatypes."  This chapter is also a covert introduction to dependent types, which are the foundation on which interesting inductive predicates are built, though we will rely on tactics to build dependently typed proof terms for us for now.  A future chapter introduces more manual application of dependent types. *)

(** * Propositional Logic *)

(** Let us begin with a brief tour through the definitions of the connectives for propositional logic.  We will work within a Coq section that provides us with a set of propositional variables.  In Coq parlance, these are just variables of type [Prop]. *)

Section Propositional.
  Variables P Q R : Prop.

  (** In Coq, the most basic propositional connective is implication, written [->], which we have already used in almost every proof.  Rather than being defined inductively, implication is built into Coq as the function type constructor.

We have also already seen the definition of [True].  For a demonstration of a lower-level way of establishing proofs of inductive predicates, we turn to this trivial theorem. *)

  Theorem obvious : True.
(* begin thide *)
    apply I.
(* end thide *)
  Qed.

  (** We may always use the [apply] tactic to take a proof step based on applying a particular constructor of the inductive predicate that we are trying to establish.  Sometimes there is only one constructor that could possibly apply, in which case a shortcut is available:%\index{tactics!constructor}% *)

(* begin thide *)
  Theorem obvious' : True.
    constructor.
  Qed.

(* end thide *)

  (** There is also a predicate [False], which is the Curry-Howard mirror image of [Empty_set] from the last chapter. *)

  Print False.
  (** %\vspace{-.15in}%[[
  Inductive False : Prop :=
  ]]

  We can conclude anything from [False], doing case analysis on a proof of [False] in the same way we might do case analysis on, say, a natural number.  Since there are no cases to consider, any such case analysis succeeds immediately in proving the goal. *)

  Theorem False_imp : False -> 2 + 2 = 5.
(* begin thide *)
    destruct 1.
(* end thide *)
  Qed.

  (** In a consistent context, we can never build a proof of [False].  In inconsistent contexts that appear in the courses of proofs, it is usually easiest to proceed by demonstrating the inconsistency with an explicit proof of [False]. *)

  Theorem arith_neq : 2 + 2 = 5 -> 9 + 9 = 835.
(* begin thide *)
    intro.

    (** At this point, we have an inconsistent hypothesis [2 + 2 = 5], so the specific conclusion is not important.  We use the %\index{tactics!elimtype}%[elimtype] tactic.  For a full description of it, see the Coq manual.  For our purposes, we only need the variant [elimtype False], which lets us replace any conclusion formula with [False], because any fact follows from an inconsistent context. *)

    elimtype False.
    (** [[
  H : 2 + 2 = 5
  ============================
   False

   ]]

   For now, we will leave the details of this proof about arithmetic to [crush]. *)

    crush.
(* end thide *)
  Qed.

  (** A related notion to [False] is logical negation. *)

  (* begin hide *)
  Definition foo := not.
  (* end hide *)

  Print not.
  (** %\vspace{-.15in}% [[
    not = fun A : Prop => A -> False
      : Prop -> Prop
     ]]

     We see that [not] is just shorthand for implication of [False].  We can use that fact explicitly in proofs.  The syntax [~ P] %(written with a tilde in ASCII)% expands to [not P]. *)

  Theorem arith_neq' : ~ (2 + 2 = 5).
(* begin thide *)
    unfold not.
    (** [[
  ============================
   2 + 2 = 5 -> False
   ]]
   *)

    crush.
(* end thide *)
  Qed.

  (** We also have conjunction, which we introduced in the last chapter. *)

  Print and.
(** %\vspace{-.15in}%[[
    Inductive and (A : Prop) (B : Prop) : Prop :=  conj : A -> B -> A /\ B
  ]]

  The interested reader can check that [and] has a Curry-Howard equivalent called %\index{Gallina terms!prod}%[prod], the type of pairs.  However, it is generally most convenient to reason about conjunction using tactics.  An explicit proof of commutativity of [and] illustrates the usual suspects for such tasks.  The operator [/\] is an infix shorthand for [and]. *)

  Theorem and_comm : P /\ Q -> Q /\ P.

(* begin thide *)
    (** We start by case analysis on the proof of [P /\ Q]. *)

    destruct 1.
    (** [[
  H : P
  H0 : Q
  ============================
   Q /\ P

   ]]

    Every proof of a conjunction provides proofs for both conjuncts, so we get a single subgoal reflecting that.  We can proceed by splitting this subgoal into a case for each conjunct of [Q /\ P].%\index{tactics!split}% *)

    split.
(** [[
2 subgoals

  H : P
  H0 : Q
  ============================
   Q

subgoal 2 is

   P

 ]]

 In each case, the conclusion is among our hypotheses, so the %\index{tactics!assumption}%[assumption] tactic finishes the process. *)

    assumption.
    assumption.
(* end thide *)
  Qed.

  (** Coq disjunction is called %\index{Gallina terms!or}%[or] and abbreviated with the infix operator [\/]. *)

  Print or.
(** %\vspace{-.15in}%[[
  Inductive or (A : Prop) (B : Prop) : Prop :=
    or_introl : A -> A \/ B | or_intror : B -> A \/ B
]]

We see that there are two ways to prove a disjunction: prove the first disjunct or prove the second.  The Curry-Howard analogue of this is the Coq %\index{Gallina terms!sum}%[sum] type.  We can demonstrate the main tactics here with another proof of commutativity. *)

  Theorem or_comm : P \/ Q -> Q \/ P.

(* begin thide *)
    (** As in the proof for [and], we begin with case analysis, though this time we are met by two cases instead of one. *)

    destruct 1.
(** [[
2 subgoals

  H : P
  ============================
   Q \/ P

subgoal 2 is

 Q \/ P

 ]]

 We can see that, in the first subgoal, we want to prove the disjunction by proving its second disjunct.  The %\index{tactics!right}%[right] tactic telegraphs this intent. *)

    right; assumption.

    (** The second subgoal has a symmetric proof.%\index{tactics!left}%

       [[
1 subgoal

  H : Q
  ============================
   Q \/ P
   ]]
   *)

    left; assumption.

(* end thide *)
  Qed.

(* begin hide *)
(* In-class exercises *)

  Theorem contra : P -> ~P -> R.
(* begin thide *)
    unfold not.
    intros.
    elimtype False.
    apply H0.
    assumption.
(* end thide *)
  Admitted.

  Theorem and_assoc : (P /\ Q) /\ R -> P /\ (Q /\ R).
(* begin thide *)
    intros.
    destruct H.
    destruct H.
    split.
    assumption.
    split.
    assumption.
    assumption.
(* end thide *)
  Admitted.

  Theorem or_assoc : (P \/ Q) \/ R -> P \/ (Q \/ R).
(* begin thide *)
    intros.
    destruct H.
    destruct H.
    left.
    assumption.
    right.
    left.
    assumption.
    right.
    right.
    assumption.
(* end thide *)
  Admitted.

(* end hide *)

  (** It would be a shame to have to plod manually through all proofs about propositional logic.  Luckily, there is no need.  One of the most basic Coq automation tactics is %\index{tactics!tauto}%[tauto], which is a complete decision procedure for constructive propositional logic.  (More on what "constructive" means in the next section.)  We can use [tauto] to dispatch all of the purely propositional theorems we have proved so far. *)

  Theorem or_comm' : P \/ Q -> Q \/ P.
(* begin thide *)
    tauto.
(* end thide *)
  Qed.

  (** Sometimes propositional reasoning forms important plumbing for the proof of a theorem, but we still need to apply some other smarts about, say, arithmetic.  The tactic %\index{tactics!intuition}%[intuition] is a generalization of [tauto] that proves everything it can using propositional reasoning.  When some further facts must be established to finish the proof, [intuition] uses propositional laws to simplify them as far as possible.  Consider this example, which uses the list concatenation operator %\coqdocnotation{%#<tt>#++#</tt>#%}% from the standard library. *)

  Theorem arith_comm : forall ls1 ls2 : list nat,
    length ls1 = length ls2 \/ length ls1 + length ls2 = 6
    -> length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2.
(* begin thide *)
    intuition.

    (** A lot of the proof structure has been generated for us by [intuition], but the final proof depends on a fact about lists.  The remaining subgoal hints at what cleverness we need to inject. *)

    (** [[
  ls1 : list nat
  ls2 : list nat
  H0 : length ls1 + length ls2 = 6
  ============================
   length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2

   ]]

   We can see that we need a theorem about lengths of concatenated lists, which we proved last chapter and is also in the standard library. *)

    rewrite app_length.
    (** [[
  ls1 : list nat
  ls2 : list nat
  H0 : length ls1 + length ls2 = 6
  ============================
   length ls1 + length ls2 = 6 \/ length ls1 = length ls2

   ]]

   Now the subgoal follows by purely propositional reasoning.  That is, we could replace [length ls1 + length ls2 = 6] with [P] and [length ls1 = length ls2] with [Q] and arrive at a tautology of propositional logic. *)

    tauto.
(* end thide *)
  Qed.

  (** The [intuition] tactic is one of the main bits of glue in the implementation of [crush], so, with a little help, we can get a short automated proof of the theorem. *)

(* begin thide *)
  Theorem arith_comm' : forall ls1 ls2 : list nat,
    length ls1 = length ls2 \/ length ls1 + length ls2 = 6
    -> length (ls1 ++ ls2) = 6 \/ length ls1 = length ls2.
    Hint Rewrite app_length.

    crush.
  Qed.
(* end thide *)

End Propositional.

(** Ending the section here has the same effect as always.  Each of our propositional theorems becomes universally quantified over the propositional variables that we used. *)

(** * What Does It Mean to Be Constructive? *)

(** One potential point of confusion in the presentation so far is the distinction between [bool] and [Prop].  The datatype [bool] is built from two values [true] and [false], while [Prop] is a more primitive type that includes among its members [True] and [False].  Why not collapse these two concepts into one, and why must there be more than two states of mathematical truth, [True] and [False]?

The answer comes from the fact that Coq implements%\index{constructive logic}% _constructive_ or%\index{intuitionistic logic|see{constructive logic}}% _intuitionistic_ logic, in contrast to the%\index{classical logic}% _classical_ logic that you may be more familiar with.  In constructive logic, classical tautologies like [~ ~ P -> P] and [P \/ ~ P] do not always hold.  In general, we can only prove these tautologies when [P] is%\index{decidability}% _decidable_, in the sense of %\index{computability|see{decidability}}%computability theory.  The Curry-Howard encoding that Coq uses for [or] allows us to extract either a proof of [P] or a proof of [~ P] from any proof of [P \/ ~ P].  Since our proofs are just functional programs which we can run, a general %\index{law of the excluded middle}%law of the excluded middle would give us a decision procedure for the halting problem, where the instantiations of [P] would be formulas like "this particular Turing machine halts."

A similar paradoxical situation would result if every proposition evaluated to either [True] or [False].  Evaluation in Coq is decidable, so we would be limiting ourselves to decidable propositions only.

Hence the distinction between [bool] and [Prop].  Programs of type [bool] are computational by construction; we can always run them to determine their results.  Many [Prop]s are undecidable, and so we can write more expressive formulas with [Prop]s than with [bool]s, but the inevitable consequence is that we cannot simply "run a [Prop] to determine its truth."

Constructive logic lets us define all of the logical connectives in an aesthetically appealing way, with orthogonal inductive definitions.  That is, each connective is defined independently using a simple, shared mechanism.  Constructivity also enables a trick called%\index{program extraction}% _program extraction_, where we write programs by phrasing them as theorems to be proved.  Since our proofs are just functional programs, we can extract executable programs from our final proofs, which we could not do as naturally with classical proofs.

We will see more about Coq's program extraction facility in a later chapter.  However, I think it is worth interjecting another warning at this point, following up on the prior warning about taking the Curry-Howard correspondence too literally.  It is possible to write programs by theorem-proving methods in Coq, but hardly anyone does it.  It is almost always most useful to maintain the distinction between programs and proofs.  If you write a program by proving a theorem, you are likely to run into algorithmic inefficiencies that you introduced in your proof to make it easier to prove.  It is a shame to have to worry about such situations while proving tricky theorems, and it is a happy state of affairs that you almost certainly will not need to, with the ideal of extracting programs from proofs being confined mostly to theoretical studies. *)

(** * First-Order Logic *)

(** The %\index{Gallina terms!forall}%[forall] connective of first-order logic, which we have seen in many examples so far, is built into Coq.  Getting ahead of ourselves a bit, we can see it as the dependent function type constructor.  In fact, implication and universal quantification are just different syntactic shorthands for the same Coq mechanism.  A formula [P -> Q] is equivalent to [forall x : P, Q], where [x] does not appear in [Q].  That is, the "real" type of the implication says "for every proof of [P], there exists a proof of [Q]."

%\index{existential quantification}\index{Gallina terms!exists}\index{Gallina terms!ex}%Existential quantification is defined in the standard library. *)

  Print ex.
(** %\vspace{-.15in}%[[
  Inductive ex (A : Type) (P : A -> Prop) : Prop :=
    ex_intro : forall x : A, P x -> ex P
    ]]

  (Note that here, as always, each [forall] quantifier has the largest possible scope, so that the type of [ex_intro] could also be written [forall x : A, (P x -> ex P)].)

  The family [ex] is parameterized by the type [A] that we quantify over, and by a predicate [P] over [A]s.  We prove an existential by exhibiting some [x] of type [A], along with a proof of [P x].  As usual, there are tactics that save us from worrying about the low-level details most of the time.

  Here is an example of a theorem statement with existential quantification.  We use the equality operator [=], which, depending on the settings in which they learned logic, different people will say either is or is not part of first-order logic.  For our purposes, it is. *)

Theorem exist1 : exists x : nat, x + 1 = 2.
(* begin thide *)
  (** remove printing exists *)
  (** We can start this proof with a tactic %\index{tactics!exists}%[exists], which should not be confused with the formula constructor shorthand of the same name.  %In the version of this document that you are reading, the reverse ``E'' appears instead of the text ``exists'' in formulas.% *)

  exists 1.

  (** The conclusion is replaced with a version using the existential witness that we announced.

     [[
  ============================
   1 + 1 = 2
   ]]
   *)

  reflexivity.
(* end thide *)
Qed.

(** printing exists $\exists$ *)

(** We can also use tactics to reason about existential hypotheses. *)

Theorem exist2 : forall n m : nat, (exists x : nat, n + x = m) -> n <= m.
(* begin thide *)
  (** We start by case analysis on the proof of the existential fact. *)

  destruct 1.
  (** [[
  n : nat
  m : nat
  x : nat
  H : n + x = m
  ============================
   n <= m

   ]]

   The goal has been replaced by a form where there is a new free variable [x], and where we have a new hypothesis that the body of the existential holds with [x] substituted for the old bound variable.  From here, the proof is just about arithmetic and is easy to automate. *)

  crush.
(* end thide *)
Qed.

(* begin hide *)
(* In-class exercises *)

Theorem forall_exists_commute : forall (A B : Type) (P : A -> B -> Prop),
  (exists x : A, forall y : B, P x y) -> (forall y : B, exists x : A, P x y).
(* begin thide *)
  intros.
  destruct H.
  exists x.
  apply H.
(* end thide *)
Admitted.

(* end hide *)

(** The tactic [intuition] has a first-order cousin called %\index{tactics!firstorder}%[firstorder], which proves many formulas when only first-order reasoning is needed, and it tries to perform first-order simplifications in any case.  First-order reasoning is much harder than propositional reasoning, so [firstorder] is much more likely than [intuition] to get stuck in a way that makes it run for long enough to be useless. *)

(** * Predicates with Implicit Equality *)

(** We start our exploration of a more complicated class of predicates with a simple example: an alternative way of characterizing when a natural number is zero. *)

Inductive isZero : nat -> Prop :=
| IsZero : isZero 0.

Theorem isZero_zero : isZero 0.
(* begin thide *)
  constructor.
(* end thide *)
Qed.

(** We can call [isZero] a%\index{judgment}% _judgment_, in the sense often used in the semantics of programming languages.  Judgments are typically defined in the style of%\index{natural deduction}% _natural deduction_, where we write a number of%\index{inference rules}% _inference rules_ with premises appearing above a solid line and a conclusion appearing below the line.  In this example, the sole constructor [IsZero] of [isZero] can be thought of as the single inference rule for deducing [isZero], with nothing above the line and [isZero 0] below it.  The proof of [isZero_zero] demonstrates how we can apply an inference rule.  (Readers not familiar with formal semantics should not worry about not following this paragraph!)

The definition of [isZero] differs in an important way from all of the other inductive definitions that we have seen in this and the previous chapter.  Instead of writing just [Set] or [Prop] after the colon, here we write [nat -> Prop].  We saw examples of parameterized types like [list], but there the parameters appeared with names _before_ the colon.  Every constructor of a parameterized inductive type must have a range type that uses the same parameter, whereas the form we use here enables us to choose different arguments to the type for different constructors.

For instance, our definition [isZero] makes the predicate provable only when the argument is [0].  We can see that the concept of equality is somehow implicit in the inductive definition mechanism.  The way this is accomplished is similar to the way that logic variables are used in %\index{Prolog}%Prolog (but worry not if not familiar with Prolog), and it is a very powerful mechanism that forms a foundation for formalizing all of mathematics.  In fact, though it is natural to think of inductive types as folding in the functionality of equality, in Coq, the true situation is reversed, with equality defined as just another inductive type!%\index{Gallina terms!eq}\index{Gallina terms!refl\_equal}% *)

Print eq.
(** %\vspace{-.15in}%[[
  Inductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : x = x
  ]]

  Behind the scenes, uses of infix [=] are expanded to instances of [eq].  We see that [eq] has both a parameter [x] that is fixed and an extra unnamed argument of the same type.  The type of [eq] allows us to state any equalities, even those that are provably false.  However, examining the type of equality's sole constructor [eq_refl], we see that we can only _prove_ equality when its two arguments are syntactically equal.  This definition turns out to capture all of the basic properties of equality, and the equality-manipulating tactics that we have seen so far, like [reflexivity] and [rewrite], are implemented treating [eq] as just another inductive type with a well-chosen definition.  Another way of stating that definition is: equality is defined as the least reflexive relation.

Returning to the example of [isZero], we can see how to work with hypotheses that use this predicate. *)

Theorem isZero_plus : forall n m : nat, isZero m -> n + m = n.
(* begin thide *)
  (** We want to proceed by cases on the proof of the assumption about [isZero]. *)

  destruct 1.
  (** [[
  n : nat
  ============================
   n + 0 = n

   ]]

   Since [isZero] has only one constructor, we are presented with only one subgoal.  The argument [m] to [isZero] is replaced with that type's argument from the single constructor [IsZero].  From this point, the proof is trivial. *)

  crush.
(* end thide *)
Qed.

(** Another example seems at first like it should admit an analogous proof, but in fact provides a demonstration of one of the most basic gotchas of Coq proving. *)

Theorem isZero_contra : isZero 1 -> False.
(* begin thide *)
  (** Let us try a proof by cases on the assumption, as in the last proof. *)

  destruct 1.
  (** [[
  ============================
   False

   ]]

   It seems that case analysis has not helped us much at all!  Our sole hypothesis disappears, leaving us, if anything, worse off than we were before.  What went wrong?  We have met an important restriction in tactics like [destruct] and [induction] when applied to types with arguments.  If the arguments are not already free variables, they will be replaced by new free variables internally before doing the case analysis or induction.  Since the argument [1] to [isZero] is replaced by a fresh variable, we lose the crucial fact that it is not equal to [0].

     Why does Coq use this restriction?  We will discuss the issue in detail in a future chapter, when we see the dependently typed programming techniques that would allow us to write this proof term manually.  For now, we just say that the algorithmic problem of "logically complete case analysis" is undecidable when phrased in Coq's logic.  A few tactics and design patterns that we will present in this chapter suffice in almost all cases.  For the current example, what we want is a tactic called %\index{tactics!inversion}%[inversion], which corresponds to the concept of inversion that is frequently used with natural deduction proof systems.  (Again, worry not if the semantics-oriented terminology from this last sentence is unfamiliar.) *)

  Undo.
  inversion 1.
(* end thide *)
Qed.

(** What does [inversion] do?  Think of it as a version of [destruct] that does its best to take advantage of the structure of arguments to inductive types.  In this case, [inversion] completed the proof immediately, because it was able to detect that we were using [isZero] with an impossible argument.

Sometimes using [destruct] when you should have used [inversion] can lead to confusing results.  To illustrate, consider an alternate proof attempt for the last theorem. *)

Theorem isZero_contra' : isZero 1 -> 2 + 2 = 5.
  destruct 1.
  (** [[
  ============================
   1 + 1 = 4

   ]]

   What on earth happened here?  Internally, [destruct] replaced [1] with a fresh variable, and, trying to be helpful, it also replaced the occurrence of [1] within the unary representation of each number in the goal.  Then, within the [O] case of the proof, we replace the fresh variable with [O].  This has the net effect of decrementing each of these numbers. *)

Abort.

(** To see more clearly what is happening, we can consider the type of [isZero]'s induction principle. *)

Check isZero_ind.
(** %\vspace{-.15in}% [[
isZero_ind
     : forall P : nat -> Prop, P 0 -> forall n : nat, isZero n -> P n
   ]]

   In our last proof script, [destruct] chose to instantiate [P] as [fun n => S n + S n = S (S (S (S n)))].  You can verify for yourself that this specialization of the principle applies to the goal and that the hypothesis [P 0] then matches the subgoal we saw generated.  If you are doing a proof and encounter a strange transmutation like this, there is a good chance that you should go back and replace a use of [destruct] with [inversion]. *)

(* begin hide *)
(* In-class exercises *)

(* EX: Define an inductive type capturing when a list has exactly two elements.  Prove that your predicate does not hold of the empty list, and prove that, whenever it holds of a list, the length of that list is two. *)

(* begin thide *)
Section twoEls.
  Variable A : Type.

  Inductive twoEls : list A -> Prop :=
  | TwoEls : forall x y, twoEls (x :: y :: nil).

  Theorem twoEls_nil : twoEls nil -> False.
    inversion 1.
  Qed.

  Theorem twoEls_two : forall ls, twoEls ls -> length ls = 2.
    inversion 1.
    reflexivity.
  Qed.
End twoEls.
(* end thide *)

(* end hide *)

(** * Recursive Predicates *)

(** We have already seen all of the ingredients we need to build interesting recursive predicates, like this predicate capturing even-ness. *)

Inductive even : nat -> Prop :=
| EvenO : even O
| EvenSS : forall n, even n -> even (S (S n)).

(** Think of [even] as another judgment defined by natural deduction rules.  The rule [EvenO] has nothing above the line and [even O] below the line, and [EvenSS] is a rule with [even n] above the line and [even (S (S n))] below.

The proof techniques of the last section are easily adapted. *)

Theorem even_0 : even 0.
(* begin thide *)
  constructor.
(* end thide *)
Qed.

Theorem even_4 : even 4.
(* begin thide *)
  constructor; constructor; constructor.
(* end thide *)
Qed.

(** It is not hard to see that sequences of constructor applications like the above can get tedious.  We can avoid them using Coq's hint facility, with a new [Hint] variant that asks to consider all constructors of an inductive type during proof search.  The tactic %\index{tactics!auto}%[auto] performs exhaustive proof search up to a fixed depth, considering only the proof steps we have registered as hints. *)

(* begin thide *)
Hint Constructors even.

Theorem even_4' : even 4.
  auto.
Qed.

(* end thide *)

(** We may also use [inversion] with [even]. *)

Theorem even_1_contra : even 1 -> False.
(* begin thide *)
  inversion 1.
(* end thide *)
Qed.

Theorem even_3_contra : even 3 -> False.
(* begin thide *)
  inversion 1.
  (** [[
  H : even 3
  n : nat
  H1 : even 1
  H0 : n = 1
  ============================
   False

   ]]

   The [inversion] tactic can be a little overzealous at times, as we can see here with the introduction of the unused variable [n] and an equality hypothesis about it.  For more complicated predicates, though, adding such assumptions is critical to dealing with the undecidability of general inversion.  More complex inductive definitions and theorems can cause [inversion] to generate equalities where neither side is a variable. *)

  inversion H1.
(* end thide *)
Qed.

(** We can also do inductive proofs about [even]. *)

Theorem even_plus : forall n m, even n -> even m -> even (n + m).
(* begin thide *)
  (** It seems a reasonable first choice to proceed by induction on [n]. *)

  induction n; crush.
  (** [[
  n : nat
  IHn : forall m : nat, even n -> even m -> even (n + m)
  m : nat
  H : even (S n)
  H0 : even m
  ============================
   even (S (n + m))

   ]]

   We will need to use the hypotheses [H] and [H0] somehow.  The most natural choice is to invert [H]. *)

  inversion H.
  (** [[
  n : nat
  IHn : forall m : nat, even n -> even m -> even (n + m)
  m : nat
  H : even (S n)
  H0 : even m
  n0 : nat
  H2 : even n0
  H1 : S n0 = n
  ============================
   even (S (S n0 + m))

   ]]

  Simplifying the conclusion brings us to a point where we can apply a constructor. *)

  simpl.
  (** [[
  ============================
   even (S (S (n0 + m)))
   ]]
   *)

  constructor.

(** [[
  ============================
   even (n0 + m)

   ]]

   At this point, we would like to apply the inductive hypothesis, which is:

   [[
  IHn : forall m : nat, even n -> even m -> even (n + m)

  ]]

  Unfortunately, the goal mentions [n0] where it would need to mention [n] to match [IHn].  We could keep looking for a way to finish this proof from here, but it turns out that we can make our lives much easier by changing our basic strategy.  Instead of inducting on the structure of [n], we should induct _on the structure of one of the [even] proofs_.  This technique is commonly called%\index{rule induction}% _rule induction_ in programming language semantics.  In the setting of Coq, we have already seen how predicates are defined using the same inductive type mechanism as datatypes, so the fundamental unity of rule induction with "normal" induction is apparent.

  Recall that tactics like [induction] and [destruct] may be passed numbers to refer to unnamed lefthand sides of implications in the conclusion, where the argument [n] refers to the [n]th such hypothesis. *)

Restart.

  induction 1.
(** [[
  m : nat
  ============================
   even m -> even (0 + m)
]]

%\noindent \coqdockw{subgoal} 2 \coqdockw{is}:%#<tt>subgoal 2 is</tt>#
[[
 even m -> even (S (S n) + m)

 ]]

 The first case is easily discharged by [crush], based on the hint we added earlier to try the constructors of [even]. *)

  crush.

  (** Now we focus on the second case: *)

  intro.
  (** [[
  m : nat
  n : nat
  H : even n
  IHeven : even m -> even (n + m)
  H0 : even m
  ============================
   even (S (S n) + m)

   ]]

   We simplify and apply a constructor, as in our last proof attempt. *)

  simpl; constructor.

(** [[
  ============================
   even (n + m)

   ]]

   Now we have an exact match with our inductive hypothesis, and the remainder of the proof is trivial. *)

  apply IHeven; assumption.

  (** In fact, [crush] can handle all of the details of the proof once we declare the induction strategy. *)

Restart.

  induction 1; crush.
(* end thide *)
Qed.

(** Induction on recursive predicates has similar pitfalls to those we encountered with inversion in the last section. *)

Theorem even_contra : forall n, even (S (n + n)) -> False.
(* begin thide *)
  induction 1.
  (** [[
  n : nat
  ============================
   False
]]

%\noindent \coqdockw{subgoal} 2 \coqdockw{is}:%#<tt>subgoal 2 is</tt>#
[[
 False

 ]]

 We are already sunk trying to prove the first subgoal, since the argument to [even] was replaced by a fresh variable internally.  This time, we find it easier to prove this theorem by way of a lemma.  Instead of trusting [induction] to replace expressions with fresh variables, we do it ourselves, explicitly adding the appropriate equalities as new assumptions. *)

Abort.

Lemma even_contra' : forall n', even n' -> forall n, n' = S (n + n) -> False.
  induction 1; crush.

  (** At this point, it is useful to consider all cases of [n] and [n0] being zero or nonzero.  Only one of these cases has any trickiness to it. *)

  destruct n; destruct n0; crush.

  (** [[
  n : nat
  H : even (S n)
  IHeven : forall n0 : nat, S n = S (n0 + n0) -> False
  n0 : nat
  H0 : S n = n0 + S n0
  ============================
   False

   ]]

  At this point it is useful to use a theorem from the standard library, which we also proved with a different name in the last chapter.  We can search for a theorem that allows us to rewrite terms of the form [x + S y]. *)

  SearchRewrite (_ + S _).
(** %\vspace{-.15in}%[[
  plus_n_Sm : forall n m : nat, S (n + m) = n + S m
     ]]
     *)

  rewrite <- plus_n_Sm in H0.

  (** The induction hypothesis lets us complete the proof, if we use a variant of [apply] that has a %\index{tactics!with}%[with] clause to give instantiations of quantified variables. *)

  apply IHeven with n0; assumption.

  (** As usual, we can rewrite the proof to avoid referencing any locally generated names, which makes our proof script more readable and more robust to changes in the theorem statement.  We use the notation [<-] to request a hint that does right-to-left rewriting, just like we can with the [rewrite] tactic. *)

  Restart.

  Hint Rewrite <- plus_n_Sm.

  induction 1; crush;
    match goal with
      | [ H : S ?N = ?N0 + ?N0 |- _ ] => destruct N; destruct N0
    end; crush.
Qed.

(** We write the proof in a way that avoids the use of local variable or hypothesis names, using the %\index{tactics!match}%[match] tactic form to do pattern-matching on the goal.  We use unification variables prefixed by question marks in the pattern, and we take advantage of the possibility to mention a unification variable twice in one pattern, to enforce equality between occurrences.  The hint to rewrite with [plus_n_Sm] in a particular direction saves us from having to figure out the right place to apply that theorem.

The original theorem now follows trivially from our lemma, using a new tactic %\index{tactics!eauto}%[eauto], a fancier version of [auto] whose explanation we postpone to Chapter 13. *)

Theorem even_contra : forall n, even (S (n + n)) -> False.
  intros; eapply even_contra'; eauto.
Qed.

(** We use a variant %\index{tactics!apply}%[eapply] of [apply] which has the same relationship to [apply] as [eauto] has to [auto].  An invocation of [apply] only succeeds if all arguments to the rule being used can be determined from the form of the goal, whereas [eapply] will introduce unification variables for undetermined arguments.  In this case, [eauto] is able to determine the right values for those unification variables, using (unsurprisingly) a variant of the classic algorithm for _unification_ %\cite{unification}%.

By considering an alternate attempt at proving the lemma, we can see another common pitfall of inductive proofs in Coq.  Imagine that we had tried to prove [even_contra'] with all of the [forall] quantifiers moved to the front of the lemma statement. *)

Lemma even_contra'' : forall n' n, even n' -> n' = S (n + n) -> False.
  induction 1; crush;
    match goal with
      | [ H : S ?N = ?N0 + ?N0 |- _ ] => destruct N; destruct N0
    end; crush.

  (** One subgoal remains:

     [[
  n : nat
  H : even (S (n + n))
  IHeven : S (n + n) = S (S (S (n + n))) -> False
  ============================
   False

   ]]

   We are out of luck here.  The inductive hypothesis is trivially true, since its assumption is false.  In the version of this proof that succeeded, [IHeven] had an explicit quantification over [n].  This is because the quantification of [n] _appeared after the thing we are inducting on_ in the theorem statement.  In general, quantified variables and hypotheses that appear before the induction object in the theorem statement stay fixed throughout the inductive proof.  Variables and hypotheses that are quantified after the induction object may be varied explicitly in uses of inductive hypotheses. *)

Abort.

(** Why should Coq implement [induction] this way?  One answer is that it avoids burdening this basic tactic with additional heuristic smarts, but that is not the whole picture.  Imagine that [induction] analyzed dependencies among variables and reordered quantifiers to preserve as much freedom as possible in later uses of inductive hypotheses.  This could make the inductive hypotheses more complex, which could in turn cause particular automation machinery to fail when it would have succeeded before.  In general, we want to avoid quantifiers in our proofs whenever we can, and that goal is furthered by the refactoring that the [induction] tactic forces us to do. *)
(* end thide *)

(* begin hide *)
(* In-class exercises *)

(* EX: Define a type [prop] of simple Boolean formulas made up only of truth, falsehood, binary conjunction, and binary disjunction.  Define an inductive predicate [holds] that captures when [prop]s are valid, and define a predicate [falseFree] that captures when a [prop] does not contain the "false" formula.  Prove that every false-free [prop] is valid. *)

(* begin thide *)
Inductive prop : Set :=
| Tru : prop
| Fals : prop
| And : prop -> prop -> prop
| Or : prop -> prop -> prop.

Inductive holds : prop -> Prop :=
| HTru : holds Tru
| HAnd : forall p1 p2, holds p1 -> holds p2 -> holds (And p1 p2)
| HOr1 : forall p1 p2, holds p1 -> holds (Or p1 p2)
| HOr2 : forall p1 p2, holds p2 -> holds (Or p1 p2).

Inductive falseFree : prop -> Prop :=
| FFTru : falseFree Tru
| FFAnd : forall p1 p2, falseFree p1 -> falseFree p2 -> falseFree (And p1 p2)
| FFNot : forall p1 p2, falseFree p1 -> falseFree p2 -> falseFree (Or p1 p2).

Hint Constructors holds.

Theorem falseFree_holds : forall p, falseFree p -> holds p.
  induction 1; crush.
Qed.
(* end thide *)

(* EX: Define an inductive type [prop'] that is the same as [prop] but omits the possibility for falsehood.  Define a proposition [holds'] for [prop'] that is analogous to [holds].  Define a function [propify] for translating [prop']s to [prop]s.  Prove that, for any [prop'] [p], if [propify p] is valid, then so is [p]. *)

(* begin thide *)
Inductive prop' : Set :=
| Tru' : prop'
| And' : prop' -> prop' -> prop'
| Or' : prop' -> prop' -> prop'.

Inductive holds' : prop' -> Prop :=
| HTru' : holds' Tru'
| HAnd' : forall p1 p2, holds' p1 -> holds' p2 -> holds' (And' p1 p2)
| HOr1' : forall p1 p2, holds' p1 -> holds' (Or' p1 p2)
| HOr2' : forall p1 p2, holds' p2 -> holds' (Or' p1 p2).

Fixpoint propify (p : prop') : prop :=
  match p with
    | Tru' => Tru
    | And' p1 p2 => And (propify p1) (propify p2)
    | Or' p1 p2 => Or (propify p1) (propify p2)
  end.

Hint Constructors holds'.

Lemma propify_holds' : forall p', holds p' -> forall p, p' = propify p -> holds' p.
  induction 1; crush; destruct p; crush.
Qed.

Theorem propify_holds : forall p, holds (propify p) -> holds' p.
  intros; eapply propify_holds'; eauto.
Qed.
(* end thide *)

(* end hide *)


(** Celia Picard with contributions by Ralph Matthes,
    I.R.I.T.,  University of Toulouse and CNRS*)

(**  provides the implementation of the type Graphs, properties
     and lemmas on it, and the development of various examples *)

Require Export Arith.
Require Import Utf8.
Require Import Setoid.
Require Import List.
Require Import Ilist.
Require Import Fin.
Require Import Morphisms.
Require Import Basics.
Require Import Tools.
Require Import ListEq.

Set Implicit Arguments.

Section Graphs_def_tools.

  Variable T: Set.
  (* Definition of coinductive graphs *)
  CoInductive Graph: Set :=
  mk_Graph: T -> (ilist Graph) -> Graph.

  Section Graphs_def_tools.
    (* Basic functions on graphs *)
    Definition label (g:Graph): T := let (t,_) := g in t.
    Definition sons (g:Graph): ilist Graph := let (_,lg) := g in lg.

    (* Some proofs to show the consistency of these definitions *)
    Lemma label_sons_OK: forall g: Graph, g = mk_Graph (label g) (sons g).
    Proof.
      intro.
      destruct g.
      reflexivity.
    Qed.

  End Graphs_def_tools.

  Section Geq_def_tools.
    Variable RelT : relation T.

    (* Definition of a relation transformer on Graph *)
    CoInductive Geq: Graph->Graph->Prop :=
      Geq_intro: forall g1 g2,
        RelT (label g1) (label g2) -> ilist_rel Geq (sons g1) (sons g2) -> Geq g1 g2.

    (* Proof that Geq preserves equivalence *)
    Lemma Geq_refl (Rrefl: Reflexive RelT): forall g: Graph, Geq g g.
    Proof.
      cofix coIH.
      intros [lab l].
      apply Geq_intro.
      { reflexivity. }
      apply (is_ilist_rel Geq l l (refl_equal _)).
      intro i.
      apply coIH.
    Qed.

    Lemma Geq_trans (Rtrans: Transitive RelT):
      forall g1 g2 g3, Geq g1 g2 -> Geq g2 g3 -> Geq g1 g3.
    Proof.
      cofix coIH.
      intros _ _ g3 [[t1 l1] g2 e1 [e1' h1]] h2 ;
        destruct h2 as [[t2 l2] [t3 l3] e2 [e2' h2]].
      apply Geq_intro.
      { apply (Rtrans _ t2) ; assumption. }
      cbn in *|-*.
      apply (is_ilist_rel Geq _ _ (trans_eq e1' e2')).
      intro i.
      assert (h3 : rewriteFins (eq_trans e1' e2') i =
        rewriteFins e2' (rewriteFins e1' i)) by treatFinPure.
      rewrite h3; clear h3.
      apply (coIH _ _ _ (h1 i) (h2 (rewriteFins e1' i))).
    Qed.

    Lemma Geq_sym (Rsym: Symmetric RelT):
      forall g1 g2: Graph, Geq g1 g2 -> Geq g2 g1.
    Proof.
      cofix coIH.
      intros _ _ [[t1 l1] [t2 l2] e1 [e2 h1]].
      apply Geq_intro ; cbn in *|-*.
      { apply Rsym, e1. }
      apply (is_ilist_rel _ _ _ (sym_eq e2)).
      intro i.
      assert (h2 := h1 (rewriteFins (eq_sym e2) i)).
      assert (h3 : rewriteFins e2 (rewriteFins (eq_sym e2) i) = i) by treatFinPure.
      rewrite h3 in h2.
      apply (coIH _ _ h2).
    Qed.

    (* Recording that Geq preserves equivalence *)
    Add Parametric Relation (Req: Equivalence RelT): (Graph) (Geq)
      reflexivity proved by (Geq_refl _)
      symmetry proved by (Geq_sym _)
      transitivity proved by (Geq_trans _)
      as GeqRel.

  End Geq_def_tools.

  Let LeqGeqRel (RelT: relation T)(Req: Equivalence RelT):= ilist_relRel (GeqRel Req).

  (* Definition of the etaExpand necessary for coinduction *)
  Section etaExpand_def_tools.
    Definition etaExpandG (g: Graph) :=
      match g with
        mk_Graph t lg => mk_Graph t lg
      end.

    Lemma etaExpandG_Identity : forall g: Graph, etaExpandG g = g.
    Proof.
      intro.
      destruct g.
      reflexivity.
    Qed.

  End etaExpand_def_tools.

  Section applyF2G_def_tools.
    (* Function that applies a function f to all the labels of a graph *)
    CoFixpoint applyF2G(f: T -> T)(g:Graph):Graph :=
      let (t,lg) := g in mk_Graph (f t) (imap (applyF2G f) lg).

  End applyF2G_def_tools.

  Section wf_def_tools.

  (* Definition of the notion of well-formedness for A and B *)
  CoInductive wfG: Graph->Prop :=
    is_wfG: forall g, (iall wfG (sons g)) -> wfG g.

  (* Theorem showing the consistency of this definition *)
  Theorem wfG_applyF2G: forall (g :Graph) (f: T -> T),
    wfG g -> wfG (applyF2G f g).
  Proof.
    cofix coIH.
    destruct g; intros f h.
    inversion_clear h as (a, H).
    cbn in H.
    apply is_wfG; cbn.
    inversion_clear i as (n', iln).
    unfold iall; cbn; intro fi.
    apply (coIH _ _ (H fi)).
  Qed.

  End wf_def_tools.

  Section Graph_in_Graph.
    (* Definition of a relation saying if a graph  is "included"
       in another graph modulo Geq *)
    (* It can be included at first level, or deeper *)
    Inductive Graph_in_Graph (RelT: relation T)(gin g: Graph): Prop :=
      is_Graph_in_Graph_dir: forall f: Fin (lgti (sons g)),
        Geq RelT gin (fcti (sons g) f) -> Graph_in_Graph RelT gin g
     | is_Graph_in_Graph_indir: forall f: Fin (lgti (sons g)),
        Graph_in_Graph RelT gin (fcti (sons g) f) -> Graph_in_Graph RelT gin g.

    Add Parametric Morphism (RelT: relation T)(R_trans: Transitive RelT)(g: Graph) :
      (Graph_in_Graph RelT g) with signature (Geq RelT) ==> (impl)
    as Graph_in_GraphM.
    Proof.
      intros g1 g2 Heq H.
      revert g2 Heq.
      induction H as [g1 f H | g1 f H IH]; intros y Heq ;
        destruct Heq as [g1 g2 e1 [e2 Heq]].
      - apply (is_Graph_in_Graph_dir g2 (rewriteFins e2 f) (Geq_trans _ H (Heq f))).
      - apply (is_Graph_in_Graph_indir g2 (rewriteFins e2 f) (IH _ (Heq f))).
    Qed.

    Add Parametric Morphism (RelT: relation T)(Req: Equivalence RelT)(g: Graph) :
      (fun x => Graph_in_Graph RelT x g) with signature (Geq RelT) ==> (impl)
    as Graph_in_GraphM2.
    Proof.
      intros g1 g2 Heq H.
      revert g2 Heq.
      induction H as [g f H | g f H IH]; intros g2 Heq.
      - apply (is_Graph_in_Graph_dir g f (Geq_trans _ (Geq_sym _ Heq) H)).
      - apply (is_Graph_in_Graph_indir g f (IH _ Heq)).
    Qed.

    (* Lemma to validate the definitions *)
    Lemma sons_in_Graph (RelT: relation T)(R_refl: Reflexive RelT): forall g: Graph,
      (forall f: Fin (lgti (sons g)), Graph_in_Graph RelT (fcti (sons g) f) g).
    Proof.
      intros g f.
      apply (is_Graph_in_Graph_dir g f (Geq_refl _ _)).
    Qed.

    Lemma GinG_sons_in_Graph (RelT: relation T): forall g1 g2,
      Graph_in_Graph RelT g1 g2 -> forall f, Graph_in_Graph RelT (fcti (sons g1) f) g2.
    Proof.
      intros g1 g2 H f.
      induction H as [g2 f' H | g2 f' H IH]; apply (is_Graph_in_Graph_indir g2 f').
      - inversion_clear H as [x i _ [H2 H3]].
        apply (is_Graph_in_Graph_dir _ (rewriteFins H2 f) (H3 _)).
      - apply IH.
    Qed.

    (* Proof of preservation of transitivity for Graph_in_Graph *)
    Lemma Graph_in_Graph_trans (RelT: relation T)(Req: Equivalence RelT):
      forall g1 g2 g3: Graph, Graph_in_Graph RelT g1 g2 -> Graph_in_Graph RelT g2 g3 ->
      Graph_in_Graph RelT g1 g3.
    Proof.
      intros g1 g2 g3 H1 H2.
      induction H1 as [g2 f H1 | g2 f H1 IH1].
      - apply (Graph_in_GraphM2 _ (Geq_sym _ H1)).
        apply (GinG_sons_in_Graph H2).
      - apply (IH1 (GinG_sons_in_Graph H2 f)).
    Qed.

  Section Graph_in_Graph_gene.
    (* Definition of a relation saying if a graph is "included"
       in another graph *)
    (* It can be included at first level, or deeper *)
    Inductive Graph_in_Graph_Gene (GRel: relation Graph)(gin g: Graph): Prop :=
      is_Graph_in_Graph_Gene_dir: GRel gin g -> Graph_in_Graph_Gene GRel gin g
     | is_Graph_in_Graph_Gene_indir: forall i: Fin (lgti (sons g)),
        Graph_in_Graph_Gene GRel gin (fcti (sons g) i) -> Graph_in_Graph_Gene GRel gin g.

    (* Lemma to validate the definitions *)

    Lemma sons_in_Graph_Gene_refl (GRel: relation Graph)(GRrefl: Reflexive GRel):
      forall g: Graph, (forall i: Fin (lgti (sons g)),
      Graph_in_Graph_Gene GRel (fcti (sons g) i) g).
    Proof.
      intros g i.
      apply (is_Graph_in_Graph_Gene_indir _ i).
      apply is_Graph_in_Graph_Gene_dir.
      reflexivity.
    Qed.

    Lemma Graph_in_Graph_Gene_refl (GRel: relation Graph)(GRrefl: Reflexive GRel)(g: Graph):
      Graph_in_Graph_Gene GRel g g.
    Proof.
      apply is_Graph_in_Graph_Gene_dir.
      reflexivity.
    Qed.

  End Graph_in_Graph_gene.

  Section GinG'.
    Definition GinG'(R: relation T) := Graph_in_Graph_Gene (Geq R).

    Lemma GinG_GinG' (R: relation T)(g1 g2 : Graph ) :
      Graph_in_Graph R g1 g2 -> GinG' R g1 g2.
    Proof.
      intros H ; induction H as [g2 i H1 |g2 i H1 IH].
      - apply (is_Graph_in_Graph_Gene_indir _ i).
        apply (is_Graph_in_Graph_Gene_dir _ _ _ H1).
      - apply (is_Graph_in_Graph_Gene_indir _ i).
        apply IH.
    Qed.

    Add Parametric Morphism(RelT: relation T)(R_trans: Transitive RelT)(g: Graph) :
      (GinG' RelT g) with signature (Geq RelT) ==> (impl)
    as GinG'M.
    Proof.
      intros g1 g2 Heq H.
      revert g2 Heq.
      induction H as [g1 H | g1 f H IH]; intros y Heq.
      - apply is_Graph_in_Graph_Gene_dir.
        apply (Geq_trans _ H Heq).
      - destruct Heq as [g1 g2 e1 [e2 Heq]].
        apply (is_Graph_in_Graph_Gene_indir g2 (rewriteFins e2 f) (IH _ (Heq f))).
    Qed.

    Add Parametric Morphism (RelT: relation T)(Req: Equivalence RelT)(g: Graph) :
      (fun x => GinG' RelT x g) with signature (Geq RelT) ==> (impl)
    as GinG'M2.
    Proof.
      intros g1 g2 Heq H.
      revert g2 Heq.
      induction H as [g H | g f H IH]; intros g2 Heq.
      - apply (is_Graph_in_Graph_Gene_dir _ _ _ (Geq_trans _ (Geq_sym _ Heq) H)).
      - apply (is_Graph_in_Graph_Gene_indir g f (IH _ Heq)).
    Qed.

    Lemma GinG'_sons_in_Graph (RelT: relation T): forall g1 g2,
      GinG' RelT g1 g2 -> forall f, GinG' RelT (fcti (sons g1) f) g2.
    Proof.
      intros g1 g2 H i.
      induction H as [g2 H | g2 i' H IH].
      - destruct H as [g1 g2 _ [H1 H2]].
        apply (is_Graph_in_Graph_Gene_indir _ (rewriteFins H1 i)), is_Graph_in_Graph_Gene_dir, H2.
      - apply (is_Graph_in_Graph_Gene_indir _ i'), IH.
    Qed.

    Lemma GinG'_trans (R: relation T)(Req: Equivalence R)(g1 g2 g3: Graph ) :
      GinG' R g1 g2 -> GinG' R g2 g3 -> GinG' R g1 g3.
    Proof.
      intros H1 H2.
      induction H1 as [g2 H1 |g2 i H1 IH].
      - apply (GinG'M2 _ (Geq_sym _ H1)), H2.
      - apply IH, GinG'_sons_in_Graph, H2.
    Qed.

  End GinG'.

  End Graph_in_Graph.

  Section Finite_def_tools.
    (* Correct coinductive definition of G_all *)
    CoInductive G_all (Pg:Graph->Prop): Graph->Prop :=
      is_Gall: forall g, Pg g -> iall (G_all Pg) (sons g) ->
        G_all Pg g.

    Definition P_Finite(RelT: relation T)(lg: list Graph):=
      fun x => exists y, In y lg /\ Geq RelT x y.

    (* Definition of G_finite indicating whether a graph is finite (possibly circular) *)
    Inductive G_finite (RelT: relation T)(g:Graph): Prop :=
      is_Gfinite: forall (lg:list Graph),
      G_all (P_Finite RelT lg) g -> G_finite RelT g.

    Add Parametric Morphism (RelT: relation T): (sons)
      with signature (Geq RelT) ==> (ilist_rel (Geq RelT))
    as sonsM.
    Proof.
      intros.
      destruct H.
      assumption.
    Qed.

    Add Parametric Morphism (RelT: relation T): (label)
      with signature (Geq RelT) ==> (RelT)
    as labelM.
    Proof.
      intros.
      destruct H.
      assumption.
    Qed.

    Definition Geq_prop_morph (RelT: relation T)(Pg: Graph -> Prop) :=
      Proper (Geq RelT ==> impl) Pg.

    Add Parametric Morphism (RelT: relation T)(Req: Equivalence RelT)(lg: list Graph):
      (P_Finite RelT lg) with signature (Geq RelT) ==> (impl)
    as P_FiniteM.
    Proof.
      intros g1 g2 H1 [g [H2 H3]].
      exists g.
      split.
      - assumption.
      - apply (Geq_trans _ (Geq_sym _ H1) H3).
    Qed.

    Lemma Geq_ilist_rel(RelT: relation T): forall g1 g2: Graph, Geq RelT g1 g2 ->
      ilist_rel (Geq RelT) (sons g1) (sons g2).
    Proof.
      intros.
      destruct H.
      assumption.
    Qed.

    Lemma G_all_Geq_eq (RelT: relation T): forall (Pg: Graph -> Prop)
        (HypPg: Geq_prop_morph RelT Pg)(g1 g2: Graph),
        Geq RelT g1 g2 -> ((G_all Pg g1) -> G_all Pg g2).
    Proof.
      intros Pg HypPg.
      cofix Hcb.
      intros g1 g2 H1 H2.
      destruct H2 as [g1 Hpb1 H2].
      unfold Geq_prop_morph in HypPg.
      apply is_Gall.
      - rewrite <- H1.
       assumption.
      - destruct H1 as [g1 g2 _ [H3 H4]].
       intro i.
       assert (H5 : i = (rewriteFins H3 (rewriteFins (sym_eq H3) i))) by treatFinPure.
       rewrite H5.
       apply (Hcb _ _ (H4 _) (H2 _)).
    Qed.

    (* Proof of the monotonicity of P_Finite *)
    Lemma P_Finite_monotone (RelT: relation T): forall (lg lg': list Graph)(g: Graph),
      incl lg lg' -> P_Finite RelT lg g -> P_Finite RelT lg' g.
    Proof.
      intros lg lg' g H1 [g' [H2 H3]].
      exists g' ; split.
      - apply (H1 g' H2).
      - assumption.
    Qed.

    (* Proof of the monotonicity of G_all with P_Finite *)
    Lemma G_all_monotone: forall (P P':Graph -> Prop)(g: Graph),
      (forall g, P g -> P' g) -> G_all P g -> G_all P' g.
    Proof.
      intros P P' g H1 ; revert g ; cofix Hc ; intros _ [g H2 H3].
      apply is_Gall.
      - apply H1, H2.
      - intro i.
        apply (Hc _ (H3 i)).
    Qed.

    Lemma G_all_P_Finite_monotone (RelT: relation T): forall (lg lg':list Graph)(g: Graph),
      incl lg lg' -> G_all (P_Finite RelT lg) g ->
      G_all (P_Finite RelT lg') g.
    Proof.
      intros lg lg' g H1.
      apply G_all_monotone.
      intros g'.
      apply P_Finite_monotone, H1.
    Qed.

    Lemma G_Finite_Geq_eq (RelT: relation T)(Req: Equivalence RelT):
      forall (g1 g2: Graph), Geq RelT g1 g2 -> ((G_finite RelT g1) ->G_finite RelT g2).
    Proof.
      intros g1 g2 H1 [l H2].
      apply (is_Gfinite (G_all_Geq_eq (P_FiniteM Req (lg := l)) H1 H2)).
    Qed.

    Lemma collectLists_G' (RelT: relation T)(Req: Equivalence RelT)(l: ilist Graph):
      iall (G_finite RelT) l -> exists lg, iall (G_all (P_Finite RelT lg)) l.
    Proof.
      intros H.
      destruct l as [n l] ; fold (mkilist l) in *|-*.
      induction n as [|n IH].
      - exists nil.
        intro i.
        inversion i.
      - assert (H1 : iall (G_finite RelT) (mkilist (fun x => l (succ x)))).
        { intro i.
          apply (H (succ i)). }
        destruct (IH _ H1) as [lg H2].
        destruct (H (first n)) as [lg' H3].
        exists (lg' ++ lg).
        unfold iall.
        intro i.
        elim (zerop (decode_Fin i)) ; intros H4.
        + rewrite (decode_Fin_0_first _ H4).
          apply (G_all_P_Finite_monotone (incl_appl lg (incl_refl _))), H3.
        + apply (G_all_P_Finite_monotone (incl_appr lg' (incl_refl _))).
          rewrite (decode_Fin_unique _ _ (decode_Fin_get_cons _ H4 : _ = decode_Fin (succ _))).
          apply (H2 (get_cons i H4)).
    Qed.

    (* Proof that if and only if g is finite,
       the graphs included in g are finite too *)
    Lemma GinG_finite_ci (RelT: relation T)(Req: Equivalence RelT):
      forall g: Graph, G_finite RelT g <-> iall (G_finite RelT) (sons g).
    Proof.
      split ;
      intros H.
      - intro f.
        destruct H as [lg H].
        apply (is_Gfinite (lg := lg)).
        destruct H as [g _ H2].
        apply (H2 f).
      - destruct (collectLists_G' _ H) as [lg H1].
        apply (is_Gfinite (lg := g :: lg)).
        apply is_Gall.
        + exists g.
          split.
          * apply in_eq.
          * apply (Geq_refl _).
        + intro i.
          apply (G_all_P_Finite_monotone (incl_tl _ (incl_refl lg))), H1.
    Qed.

    Lemma G_all_G_in_G_P(RelT: relation T)(Req: Equivalence RelT):
       forall (P: Graph -> Prop)(HypP: Geq_prop_morph RelT P)(g: Graph),
       G_all P g -> (forall gin,  Graph_in_Graph RelT gin g -> P gin).
    Proof.
      intros P HypP _ [g _ Hall] gin Hin.
      unfold Geq_prop_morph in HypP.
      induction Hin as [g f Hin | g f Hin IH].
      - rewrite <- (Geq_sym _ Hin).
        destruct (Hall f) as [g' HPg _].
        assumption.
      - destruct (Hall f) as [g'  _ H].
        apply (IH H).
    Qed.

    Lemma G_finite_All_G_in_G_finite (RelT: relation T)(Req: Equivalence RelT):
      forall g: Graph, G_all (G_finite RelT) g -> (forall gin: Graph,
      Graph_in_Graph RelT gin g -> G_finite RelT gin).
    Proof.
      apply (G_all_G_in_G_P _).
      intros g1 g2 H1 H2.
      apply (G_Finite_Geq_eq _ H1 H2).
    Qed.

    Lemma G_finite_All_G_in_G_finite' (RelT: relation T)(Req: Equivalence RelT):
      forall g: Graph, G_finite RelT g -> (forall gin: Graph,
      Graph_in_Graph RelT gin g -> G_finite RelT gin).
    Proof.
      intros g H1 gin H2.
      induction H2 as [g f H3 | g f _ IH] ;
      destruct (GinG_finite_ci _ g) as [H2 _].
      - apply (G_Finite_Geq_eq _ (Geq_sym _ H3)).
        apply (H2 H1 f).
      - apply (IH (H2 H1 f)).
    Qed.

  End Finite_def_tools.
End Graphs_def_tools.

Section Graphs_of_nat.
  Section Theorem_for_infinity_gene.

    Definition morph_f (T: Set)(R: relation T)(f: T -> nat):=
      Proper (R ==> eq(A := nat)) f.

    Definition mf (T: Set)(R: relation T)(f: T -> nat) :=
      forall g1 g2, R g1 g2 -> f g1 = f g2.

    Lemma finite_bounded :
     forall (T: Set)(RelT: relation T)(g: Graph T)(f: Graph T -> nat)
     (hm: morph_f (Geq RelT) f), G_finite RelT g -> exists m,
     G_all (fun x => f x <= m) g.
    Proof.
      intros T RelT g f hm [lg H].
      exists (max_list_nat (map f lg)).
      revert g H.
      cofix Hc.
      intros _ [g [g' [H1 H2]] H].
      apply is_Gall.
      - rewrite (hm _ _ H2).
        apply (max_list_max (map f lg) _ (in_map _ _ _ H1)).
      - intro i.
        apply (Hc _ (H i)).
    Qed.

    Lemma morph_f_label_nat : morph_f (Geq (@eq nat)) (@label nat).
    Proof.
      intros _ _ [g1 g2 e _].
      assumption.
    Qed.

    Lemma finite_label_bounded : forall g: Graph nat,
      G_finite (@eq nat) g -> exists m, G_all (fun x => (label x <= m)) g.
    Proof.
      intros g H.
      apply (finite_bounded morph_f_label_nat H).
    Qed.

    Lemma morph_f_nb_sons (T: Set)(RelT: relation T) :
      morph_f (Geq RelT) (fun x => lgti (sons x)).
    Proof.
      intros _ _ [g1 g2 _ [e _]].
      assumption.
    Qed.

    Lemma finite_ilist_bounded (T: Set)(RelT: relation T):
      forall g: Graph T, G_finite RelT g ->
      exists m, G_all ((fun x => lgti (sons x) <= m)) g.
    Proof.
      intros g H.
      apply (finite_bounded (@morph_f_nb_sons T RelT) H).
    Qed.

  End Theorem_for_infinity_gene.

  Section Theorem_for_infinity.

    Definition Pg_label_bound(m: nat) := (fun x : Graph nat => label x <= m).

    Add Parametric Morphism (m: nat): (Pg_label_bound m)
      with signature (Geq (@eq nat) ==> impl)
      as Pg_label_boundM.
    Proof.
      intros a1 a2 Heq H.
      destruct Heq as [a1 a2 e _].
      unfold Pg_label_bound.
      rewrite <- e.
      assumption.
    Qed.

    Lemma infinite_unbounded :
     forall (T: Set)(RelT: relation T)(g: Graph T)(f: Graph T -> nat)
     (hm: morph_f (Geq RelT) f), not (exists m,
     G_all (fun x => f x <= m) g) -> not (G_finite RelT g).
    Proof.
      intros T RelT g f H1 H2 H3.
      apply H2.
      apply (finite_bounded H1 H3).
    Qed.

    (* contrapositive of the previous lemma *)
    Lemma unbounded_infiniteGraph :
      forall g: Graph nat, not (exists m, G_all (Pg_label_bound m) g) ->
      not (G_finite (@eq nat) g).
    Proof.
      intros g H1.
      apply (infinite_unbounded morph_f_label_nat H1).
    Qed.

    Definition Pg_ilist_bound (T: Set) (m: nat): Graph T -> Prop:=
      fun x: Graph T => lgti (sons x) <= m.

    (* contrapositive of the previous lemma *)
    Lemma ilist_unbounded_infiniteGraph : forall (T: Set)(RelT: relation T),
      forall g: Graph T, not (exists m,  G_all (Pg_ilist_bound m) g) ->
      not (G_finite RelT g).
    Proof.
      intros T RelT g.
      apply infinite_unbounded.
      apply morph_f_nb_sons.
    Qed.

  End Theorem_for_infinity.

Section Examples.

  Section Finite_example.

     (* Example of a finite graph *)
     Definition finite_example: Graph nat.
     Proof.
       cofix Hc.
       exact (mk_Graph 0 (singleton (mk_Graph 1 (singleton Hc)))).
     Defined.

    (* Proof that it is finite *)
    Lemma finite_example_finite: G_finite (@eq nat) finite_example.
    Proof.
      apply (is_Gfinite (lg :=
        finite_example :: (mk_Graph 1 (singleton finite_example)) ::nil)).
      cofix Hc.
      apply is_Gall.
      - exists finite_example.
        split.
        + apply in_eq.
        + apply (Geq_refl _).
      - intro f.
        apply is_Gall.
        + exists (fcti (sons finite_example) (first 0)).
          split.
          * right ; left; reflexivity.
          * apply (Geq_refl _).
        + unfold iall.
          cbn.
          intro f'.
          apply Hc.
    Qed.

    Definition finite_example_unfolded: Graph nat.
    Proof.
      cofix Hc.
      exact (mk_Graph 0 (singleton (mk_Graph 1
        (singleton (mk_Graph 0 (singleton (mk_Graph 1 (singleton Hc)))))))).
    Defined.

   Lemma finite_example_Geq_finite_example_unfolded:
     Geq (@eq _) finite_example finite_example_unfolded.
    Proof.
      cofix Hc.
      assert (H :forall (T: Set) (a1 a2: T), lgti (singleton a1) = lgti (singleton a2)).
      { intros T a1 a2 ; reflexivity. }
      do 4 (apply Geq_intro ; try reflexivity ; cbn ;
        apply (is_ilist_rel _ _ _ (H _ _ _)) ;
        cbn ; intro f ; clear f).
      apply Hc.
    Qed.

  End Finite_example.

  Section Infinite_example.

     (* Example of an infinite graph (whose labels are unbounded) *)
    Definition infinite_graph_gene: forall (n: nat), Graph nat.
    Proof.
      cofix Hc.
      intros n.
      exact (mk_Graph n (singleton (Hc (S n)))).
    Defined.

    Lemma infinite_graph_gene_n_inc_Sn: forall n: nat,
      Geq (@eq nat) (fcti (sons (infinite_graph_gene n)) (first 0))
        (infinite_graph_gene (S n)).
    Proof.
      intros n.
      apply (Geq_refl _).
    Qed.

    Lemma infinite_graph_gene_Sn_in_n: forall n : nat,
      Graph_in_Graph (@eq nat) (infinite_graph_gene (S n)) (infinite_graph_gene n).
    Proof.
      intros n.
      apply (is_Graph_in_Graph_dir _ (first _ : Fin (lgti (sons (infinite_graph_gene n))))).
      apply (Geq_refl _).
    Qed.

    Lemma infinite_example_gene_n_inc_all: forall n m: nat,
      n < m -> Graph_in_Graph (@eq _) (infinite_graph_gene m) (infinite_graph_gene n).
    Proof.
      intros n m H.
      induction m as [| m IHm].
      { inversion H. }
      elim (le_lt_eq_dec n m (lt_n_Sm_le _ _ H)); intros h.
      - apply (Graph_in_Graph_trans (@eq_equivalence _) (infinite_graph_gene_Sn_in_n m)
          (IHm h)).
      - rewrite h.
       apply infinite_graph_gene_Sn_in_n.
    Qed.

    Lemma infinite_example_gene_unbounded : forall n: nat,
      not (exists m, G_all (fun x => label x <= m) (infinite_graph_gene n)).
    Proof.
      intros n [m H].
      inversion H as [g h H0 e].
      clear g e H0.
      cbn in *|-*.
      assert (Hin := infinite_example_gene_n_inc_all (le_gt_S _ _ h)).
      assert (S m <= m).
      { apply (G_all_G_in_G_P (@eq_equivalence _) (@Pg_label_boundM m) H Hin). }
      apply (le_Sn_n _ H0).
    Qed.

    (* Proof that it is infinite *)
    Lemma infinite_example_infinite: forall n: nat,
      not (G_finite (@eq _) (infinite_graph_gene n)).
    Proof.
      intros n.
      apply unbounded_infiniteGraph.
      unfold Pg_label_bound.
      apply (infinite_example_gene_unbounded n).
    Qed.

  End Infinite_example.

  Section Infinite_example_bounded.

    Fixpoint addn0 (n: nat) (g: Graph nat) : Graph nat :=
      match n with
        O =>  g
      | S m => mk_Graph 0 (singleton (addn0 m g))
      end.

    Definition add11 (g: Graph nat): Graph nat := mk_Graph 1 (singleton g).

    Definition addn011 (n: nat) (g: Graph nat): Graph nat :=
      (addn0 n (add11 g)).

    Definition inf_ex_bounded_gene_aux : forall (n: nat)(m: nat), Graph nat.
    Proof.
      cofix Hc.
      intros n m.
      destruct m as [| m].
      - exact (add11 (Hc (S n) (S n))).
      - exact (mk_Graph 0 (singleton (Hc n m))).
    Defined.

     (* Example of an infinite graph (whose labels and length of sons are bounded) *)
    Definition inf_ex_bounded_gene (n: nat) : Graph nat :=
      inf_ex_bounded_gene_aux n n.

  Lemma not_minus_O_le: forall (m n: nat), m -n =0 -> m <= n.
  Proof.
    intros n m H.
    apply not_lt.
    intros H1.
    rewrite (minus_n_m_0 (lt_le_weak _ _ H1) H) in H1.
    apply (lt_irrefl _ H1).
  Qed.

  Lemma list_not_infinite' : forall (lg: list (Graph nat))(seq: nat -> Graph nat),
    (forall (n m:nat), Geq (@eq _) (seq n)(seq(n+m)) -> m=0) ->
    (forall (n:nat), n <= length lg -> ~~P_Finite (@eq _) lg (seq n)) -> False.
  Proof.
    induction lg as [|g lg IH]; intros seq H1 H2.
    - apply (H2 0 (le_refl 0)).
      intros [g [H3 _]].
      inversion H3.
    - (* the following first part of the proof is based on a simple intuitive argument:
         not all elements up to index length lg can be in P_Finite lg,
         hence one of them must be bisimilar with g
       *)
      apply (IH _ H1).
      intros n H3 H4.
      apply (H2 _ (lt_le_weak _ _ (le_lt_n_Sm _ _ H3))) ; intro H0.
      assert (H5: Geq (@eq _) (seq n) g).
      { destruct H0 as [g' [[H5|H5] H6]];
          [rewrite H5 | destruct H4 ; exists g' ; split]; assumption. }
      (* also the following second part of the proof is based on a simple intuitive argument:
         If we throw this element (seq x) out, the remaining sequence has all elements up to index
         length lg in P_Finite lg since g is already taken. Now, this is a contradiction.
       *)

      (* first some preparations *)
      set (seq' := fun x: nat => if (le_lt_dec n x) then seq (S x) else seq x).
      assert (seq'Prop: (forall x: nat, x < n -> seq' x = seq x) /\
         (forall x: nat, n <= x -> seq' x = seq (S x))).
      { split ; intros x h ; unfold seq'; elim (le_lt_dec n x) ; intro a ; try reflexivity ;
          [assert (h1 := (le_lt_trans n x n a h)) | assert (h1 := (le_lt_trans n x n h a))] ;
            elim (lt_irrefl _ h1). }
      destruct seq'Prop as [seq'Prop1 seq'Prop2].
      assert (H6 : (∀n m : nat, Geq (@eq _) (seq' n) (seq' (n + m)) → m = 0)).
      { (* seq' is a sub-sequence of seq, so
           forall n m : nat, Geq (seq' n) (seq' (n + m)) -> m = 0
           is a consequence of the same property for seq *)
        intros n' m H6.
        destruct (le_lt_dec n (n'+m)) as [h1|h1].
        + rewrite (seq'Prop2 _ h1) in H6.
          destruct (le_lt_dec n n') as [h2 |h2].
          * rewrite (seq'Prop2 _ h2) in H6.
            rewrite <- plus_Sn_m in H6.
            apply (H1 (S n') _ H6).
          * rewrite (seq'Prop1 _ h2) in H6.
            rewrite plus_n_Sm in H6.
            elim (O_S _ (sym_eq (H1 _ _ H6))).
        + do 2 rewrite seq'Prop1 in H6 ; try exact h1 ;
             try exact (le_lt_trans _ _ _ (le_plus_l n' m) h1).
          apply (H1 _ _ H6).
      }
      (* we can now carry out the second step of the proof *)
      apply (IH _ H6).
      intros n' H7 H8.
      destruct (le_lt_dec n n') as [h1|h1'];
       [rewrite (seq'Prop2 _ h1) in H8 ; destruct (H2 (S n') (le_n_S _ _ H7))
       | rewrite (seq'Prop1 _ h1') in H8 ; set (h1 := lt_le_weak _ _ h1');
         destruct (H2 n' (le_S _ _ H7))];
       intros  [g0 [[Hyp1|Hyp1] Hyp2]] ; apply H8;
       try (exists g0 ; split; assumption) ; rewrite <- Hyp1 in Hyp2 ;
       assert (H10:=(GeqRel_Transitive (@eq_equivalence _) H5
         (GeqRel_Symmetric (@eq_equivalence _) Hyp2)));
       rewrite (le_plus_minus _ _ h1) in H10.
      + rewrite plus_n_Sm in H10.
        elim (O_S _ (sym_eq (H1 _ _ H10))).
      + elim (lt_irrefl _ (le_lt_trans n n' n
         (not_minus_O_le _ _ (H1 _ _ (GeqRel_Symmetric (@eq_equivalence _) H10))) h1')).
Qed.

  Lemma list_not_infinite: forall (lg: list (Graph nat))(seq: nat -> Graph nat),
    (forall (n m:nat), Geq (@eq _) (seq n)(seq(n+m)) -> m=0) ->
    (forall (n:nat), n <= length lg -> P_Finite (@eq _)lg (seq n)) -> False.
  Proof.
    intros lg seq H1 H2.
    apply (@list_not_infinite' lg seq H1).
    intros n h H3.
    apply H3.
    apply (H2 n h).
  Qed.

  Lemma inf_ex_bounded_gene_aux_0 : forall (n: nat),
    inf_ex_bounded_gene_aux n 0 =
    mk_Graph 1 (singleton (inf_ex_bounded_gene_aux (S n) (S n))).
  Proof.
    intros n.
    rewrite <- (etaExpandG_Identity (inf_ex_bounded_gene_aux n 0)).
    reflexivity.
  Qed.

  Lemma inf_ex_bounded_gene_aux_S : forall (n m: nat),
    inf_ex_bounded_gene_aux n (S m) =
    mk_Graph 0 (singleton (inf_ex_bounded_gene_aux n m)).
  Proof.
    intros n m.
    rewrite <- (etaExpandG_Identity (inf_ex_bounded_gene_aux n (S m))).
    reflexivity.
  Qed.

  Lemma inf_ex_bounded_gene_aux_addn011: forall (n m: nat),
    inf_ex_bounded_gene_aux n m = addn011 m (inf_ex_bounded_gene_aux (S n)(S n)).
  Proof.
    intro n.
    induction m as [|m IHm].
    - apply inf_ex_bounded_gene_aux_0.
    - rewrite inf_ex_bounded_gene_aux_S.
      rewrite IHm.
      unfold addn011 at 2.
      reflexivity.
  Qed.

  Lemma inf_ex_bounded_gene_addn011: forall n,
    inf_ex_bounded_gene n = addn011 n (inf_ex_bounded_gene (S n)).
  Proof.
    intro n.
    unfold inf_ex_bounded_gene.
    apply inf_ex_bounded_gene_aux_addn011.
  Qed.

  Lemma addn011_Geq : forall (g1 g2: Graph nat)(n: nat),
    Geq (@eq _) g1 g2 -> Geq (@eq _) (addn011 n g1) (addn011 n g2).
  Proof.
    intros g1 g2 n H.
    induction n as [|n IHn].
    - apply Geq_intro.
      { reflexivity. }
      assert (h : lgti (singleton g1) = lgti (singleton g2)).
      { reflexivity. }
      apply (is_ilist_rel _ _ _ h).
      intro f.
      assumption.
    - cbn.
      apply Geq_intro.
      { reflexivity. }
      assert (h : lgti (singleton (addn011 n g1)) = lgti (singleton (addn011 n g2))).
      { reflexivity. }
      apply (is_ilist_rel _ _ _ h).
      intro f.
      assumption.
  Qed.

  Lemma addn0comp : forall (n1 n2: nat)(g: Graph nat),
    addn0 n1 (addn0 n2 g) = addn0 (n1+n2) g.
  Proof.
    induction n1 as [|n1 IHn].
    { reflexivity. }
    intros n2 g.
    cbn.
    rewrite IHn.
    reflexivity.
  Qed.

  Lemma addn0_Geq_inv: forall (n: nat)(g1 g2: Graph nat),
    Geq (@eq _) (addn0 n g1)(addn0 n g2) -> Geq (@eq _) g1 g2.
  Proof.
    intros n g1 g2 H.
    induction n as [|n IHn] ;
    inversion H as [g3 g4 e1 [e H1] h1 h2] ;
    clear g3 g4 e1 h1 h2.
    - assumption.
    - cbn in H1.
      apply (IHn (H1 (first _))).
  Qed.

  Lemma addn0_Geq: forall (n: nat)(g1 g2: Graph nat),
   Geq (@eq _) g1 g2 ->  Geq (@eq _) (addn0 n g1)(addn0 n g2).
  Proof.
    induction n as [|n IH]; intros g1 g2 H.
    - apply H.
    - apply Geq_intro.
      { reflexivity. }
      cbn.
      apply (is_ilist_rel _ _ _ (refl_equal _ :
         lgti (singleton (addn0 n g1)) = lgti(singleton (addn0 n g2)))).
      cbn.
      intro i ; apply IH, H.
  Qed.

  Lemma inf_ex_bounded_gene_inj (n m: nat):
    Geq (@eq _) (inf_ex_bounded_gene n)(inf_ex_bounded_gene (n+m)) -> m=0.
  Proof.
    destruct m.
    { reflexivity. }
    intro.
    rewrite inf_ex_bounded_gene_addn011 in H.
    rewrite (inf_ex_bounded_gene_addn011 (n + S m)) in H.
    unfold addn011 in H.
    rewrite <- addn0comp in H.
    apply addn0_Geq_inv in H.
    inversion H as [g3 g4 e1 h0 h1 h2] ; inversion e1.
  Qed.

  Lemma G_all_addn0_inv: forall (lg: list (Graph nat))(g: Graph nat)(n: nat),
    G_all (P_Finite (@eq _) lg) (addn0 n g) ->
    G_all (P_Finite (@eq _) lg) g.
  Proof.
    intros lg g n H.
    induction n as [|n IHn].
    { assumption. }
    inversion H as [g' Hp Hall e].
    apply (IHn (Hall (first 0))).
  Qed.

  Lemma G_all_add11_inv: forall (lg: list (Graph nat))(g: Graph nat),
    G_all (P_Finite (@eq _) lg) (add11 g) ->  G_all (P_Finite (@eq _) lg) g.
  Proof.
    intros lg g H.
    inversion H as [g' Hp Hall e].
    apply (Hall (first 0)).
  Qed.

  Lemma G_all_addn011_inv: forall (lg: list (Graph nat))(g: Graph nat)(n: nat),
    G_all (P_Finite (@eq _) lg) (addn011 n g) ->  G_all (P_Finite (@eq _) lg) g.
  Proof.
    intros lg g n H.
    apply (G_all_add11_inv (G_all_addn0_inv _ _ H)).
  Qed.

  Lemma inf_ex_bounded_geneelements_aux: forall (n: nat)(lg: list (Graph nat)),
    G_all (P_Finite (@eq _) lg) (inf_ex_bounded_gene n) ->
    forall m: nat, G_all (P_Finite (@eq _) lg) (inf_ex_bounded_gene (n+m)).
  Proof.
    intros n lg Hyp m. revert n Hyp.
    induction m as [|m IHm]; intros n Hyp.
    - rewrite <- plus_n_O.
      assumption.
    - rewrite <- plus_n_Sm.
      assert (H:= IHm _ Hyp).
      rewrite inf_ex_bounded_gene_addn011 in H.
      apply (G_all_addn011_inv _ _ H).
  Qed.

  Lemma inf_ex_bounded_geneelements: forall (n: nat)(lg: list (Graph nat)),
    G_all (P_Finite (@eq _) lg) (inf_ex_bounded_gene n) ->
    forall m: nat, P_Finite (@eq _) lg (inf_ex_bounded_gene (n+m)).
  Proof.
    intros n lg H m.
    assert (H0:= inf_ex_bounded_geneelements_aux _ H m).
    inversion H0.
    assumption.
  Qed.

    (* proof that it is infinite *)
    Theorem inf_ex_bounded_gene_infinite: forall (n: nat),
      not (G_finite (@eq _) (inf_ex_bounded_gene n)).
    Proof.
      intros n H.
      inversion H as [lg Hall].
      apply (list_not_infinite (lg:=lg) (fun m:nat => inf_ex_bounded_gene (n+m))).
      - intros n' m H1.
        rewrite plus_assoc in H1.
        apply inf_ex_bounded_gene_inj in H1.
        assumption.
      - intros n' Hle.
        apply (inf_ex_bounded_geneelements _ Hall).
    Qed.

    Definition ilist_n0 (n: nat) := mkilist (fun i : Fin n => 0).

    (* Compression of inf_ex_bounded_gene *)
    CoFixpoint inf_ex_bounded_gene' (n : nat) : Graph (ilist nat) :=
      mk_Graph (ilist_n0 n) (singleton (inf_ex_bounded_gene' (S n))).

    Definition nb_O (g: Graph (ilist nat)) : nat :=
      match g with
        mk_Graph l _ => lgti l
      end.

    Lemma  inf_ex_bounded_gene'_Sn_n (n: nat):
      Graph_in_Graph eq (inf_ex_bounded_gene' (S n)) (inf_ex_bounded_gene' n).
    Proof.
      apply (is_Graph_in_Graph_dir _ (first _ : Fin (lgti (sons (inf_ex_bounded_gene' n))))).
      apply (Geq_refl _).
    Qed.

    Lemma inf_ex_bounded_gene'_m_n (n m : nat): n < m ->
      Graph_in_Graph eq (inf_ex_bounded_gene' m) (inf_ex_bounded_gene' n).
    Proof.
      intros H.
      induction m as [| m IHm].
      { inversion H. }
      elim (le_lt_eq_dec n m (lt_n_Sm_le _ _ H)); intros h.
      - apply (Graph_in_Graph_trans (@eq_equivalence _) (inf_ex_bounded_gene'_Sn_n _)
          (IHm h)).
      - rewrite h.
        apply inf_ex_bounded_gene'_Sn_n.
    Qed.

    Theorem inf_ex_bounded_gene'_infinite: forall (n: nat),
      not (G_finite (@eq _) (inf_ex_bounded_gene' n)).
    Proof.
      intros n.
      assert (H1 := @infinite_unbounded _ eq (inf_ex_bounded_gene' n) nb_O).
      assert (H2 : morph_f (Geq eq) nb_O).
      { intros _ _ [[lab1 l1] [lab2 l2] H2 _].
        cbn in *|-*.
        rewrite H2.
        reflexivity. }
      apply (H1 H2) ; clear H1.
      intros [m H3].
      inversion H3.
      assert (H4 : S m <= m).
      { assert (H5 : forall m x y, Geq eq x y -> impl (nb_O x <= m) (nb_O y <= m)).
        { intros m' _ _ [[labx lx] [laby ly] H4 H5] H6.
          cbn in *|-*.
          rewrite <- H4 ; assumption. }
        rewrite (refl_equal _ : S m = nb_O (inf_ex_bounded_gene' (S m))).
        apply (G_all_G_in_G_P _ (H5 m) H3).
        apply inf_ex_bounded_gene'_m_n, le_gt_S, H.
      }
      apply (le_Sn_n _ H4).
    Qed.

  End Infinite_example_bounded.

End Examples.

Definition is_cycle (T: Set)(RelT: relation T) (g: Graph T): Prop :=
  Graph_in_Graph RelT g g.

Lemma finite_example_is_cycle : is_cycle (@eq _) finite_example.
Proof.
  apply (is_Graph_in_Graph_indir finite_example (first 0)).
  apply (is_Graph_in_Graph_dir (mk_Graph 1 (singleton finite_example)) (first 0)).
  apply (Geq_refl _).
Qed.

Inductive hasCycle (T: Set)(RelT: relation T)(g: Graph T): Prop :=
  hasCycle_dir: is_cycle RelT g -> hasCycle RelT g
| hasCycle_indir: forall f, hasCycle RelT (fcti (sons g) f) -> hasCycle RelT g.

Lemma finite_example_has_cycle: hasCycle (@eq _) finite_example.
Proof.
  apply hasCycle_dir.
  apply finite_example_is_cycle.
Qed.

Definition JustOneLeaf (n: nat) := mk_Graph n (inil (Graph nat)).

Lemma JustOneLeaf_not_cycle: forall n: nat, not (hasCycle (@eq _) (JustOneLeaf n)).
Proof.
  intros n [[f H |f H]|f H];
  inversion f.
Qed.

Lemma JustOneLeaf_finite (n: nat) : G_finite eq (JustOneLeaf n).
Proof.
  apply (is_Gfinite (lg := JustOneLeaf n :: nil)).
  apply is_Gall.
  - exists (JustOneLeaf n).
    split.
    + left ; reflexivity.
    + apply (Geq_refl _).
  - unfold iall.
    cbn.
    intro i.
    inversion i.
Qed.

CoFixpoint three_nodes_graph: Graph nat :=
  mk_Graph 1 (icons (mk_Graph 3 (icons three_nodes_graph (inil (Graph nat))))
                    (icons (mk_Graph 2 (inil (Graph nat))) (inil (Graph nat)))).

Lemma three_nodes_graph_hasCycle: hasCycle (@eq _) three_nodes_graph.
Proof.
  apply hasCycle_dir.
  apply (is_Graph_in_Graph_indir three_nodes_graph (first 1)).
  apply (is_Graph_in_Graph_dir (fcti (sons three_nodes_graph) (first 1)) (first 0)).
  apply (Geq_refl _).
Qed.

Definition three_nodes_graph_bis: Graph nat.
Proof.
  set (g2 := mk_Graph 2 (inil (Graph nat))).
  set (g3 := mk_Graph 3 (icons g2 (inil (Graph nat)))).
  exact (mk_Graph 1 (icons g2 (icons g3 (inil (Graph nat))))).
Defined.

Lemma three_nodes_graph_bis_not_hasCycle: not (hasCycle (@eq _) three_nodes_graph_bis).
Proof.
  intros [[f  |f ]| f ];
  elim (zerop (decode_Fin f)) ; intros a ;
  try assert (h:= (le_antisym _ _ (gt_S_le _ _ (decode_Fin_inf_n f)) (gt_le_S _ _ a))) ;
  try assert (h := a) ;
  try assert (H2 := decode_Fin_unique _ _ (h: _ = decode_Fin (first _)) : f = first 1) ;
  try assert (H2 := decode_Fin_unique _ _ (h: _ = decode_Fin (succ (first 0))) :
    f = succ (first 0)) ;
  cbn in f, H ; rewrite H2 in H; clear f h H2 a;
  try (inversion H as [g1 g2 e H1 H3 H4] ; inversion e) ;
  try (destruct H as [f' | f'] ;
  rewrite (Fin_first_1 f') in H ; clear f' ;
  try (inversion H as [g1 g2 e H1 H3 H4] ; inversion e)) ;
  try (destruct H as [[f H | f H] |f H] ; cbn in H ; rewrite (Fin_first_1 f) in H ;
    clear f) ;
  try (inversion H as [g1 g2 e H1 H3 H4] ; inversion e) ;
  try (destruct H as [[f H| f H] | f H] ; inversion f) ;
  destruct H as [f H | f H] ; inversion f.
Qed.

CoFixpoint two_nodes_cycle: Graph nat :=
  mk_Graph 2 (icons (mk_Graph 3 (icons two_nodes_cycle (inil (Graph nat))))
                    (inil (Graph nat))).

Lemma two_nodes_cycle_hasCycle: hasCycle (@eq _) two_nodes_cycle.
Proof.
  apply hasCycle_dir.
  apply (is_Graph_in_Graph_indir _ (first 0 : Fin (lgti (sons two_nodes_cycle)))).
  apply (is_Graph_in_Graph_dir _ (first 0 : Fin (lgti (sons (fcti (sons two_nodes_cycle) (first 0)))))).
  apply (Geq_refl _).
Qed.

Definition three_nodes_graph_ter: Graph nat :=
  mk_Graph 1 (icons two_nodes_cycle
                   (icons (mk_Graph 3 (icons two_nodes_cycle (inil (Graph nat))))
                          (inil (Graph nat)))).

Lemma three_nodes_graph_ter_hasCycle: hasCycle (@eq _) three_nodes_graph_ter.
Proof.
  apply (hasCycle_indir _ (first 1 : Fin (lgti (sons three_nodes_graph_ter)))).
  apply hasCycle_dir.
  apply (is_Graph_in_Graph_indir (fcti (sons three_nodes_graph_ter) (first 1)) (first 0)).
  apply (is_Graph_in_Graph_dir
    (fcti (sons (fcti (sons three_nodes_graph_ter) (first 1))) (first 0)) (first 0)) .
  apply (Geq_refl _).
Qed.

Lemma three_nodes_graph_ter_hasCycle2: hasCycle (@eq _) three_nodes_graph_ter.
Proof.
  apply (hasCycle_indir _ (succ (first 0) : Fin (lgti (sons three_nodes_graph_ter)))).
  apply hasCycle_dir.
  apply (is_Graph_in_Graph_indir (fcti (sons three_nodes_graph_ter) (succ (first 0)))
    (first 0)).
  apply (is_Graph_in_Graph_dir
    (fcti (sons (fcti (sons three_nodes_graph_ter) (succ (first 0)))) (first 0))
    (first 0)) .
  apply (Geq_refl _).
Qed.

Definition three_nodes_graph4: Graph nat.
Proof.
  cofix g1.
  set (g3 := mk_Graph 3 (icons g1 (inil (Graph nat)))).
  set (g2 := mk_Graph 2 (icons g3 (inil (Graph nat)))).
  exact (mk_Graph 2 (icons g2 (inil (Graph nat)))).
Defined.

Lemma three_nodes_graph4_hasCycle: hasCycle (@eq _) three_nodes_graph4.
Proof.
  apply hasCycle_dir.
  apply (is_Graph_in_Graph_indir three_nodes_graph4 (first 0)).
  apply (is_Graph_in_Graph_indir (fcti (sons three_nodes_graph4) (first 0)) (first 0)).
  apply (is_Graph_in_Graph_dir
    (fcti (sons (fcti (sons three_nodes_graph4) (first 0))) (first 0))
    (first 0) (Geq_refl _ _)).
Qed.

End Graphs_of_nat.

Section hasCycle'.

  Inductive hasCycle'(T: Set)(RelT: relation T)(g: Graph T) : Prop :=
    hasCycle'_intro : forall (g': Graph T), is_cycle RelT g' -> GinG' RelT g' g -> hasCycle' RelT g.

    Lemma hasCycle'_sons (T: Set)(RelT: relation T)(Req: Equivalence RelT)(g: Graph T)
      (i: Fin (lgti (sons g))): hasCycle' RelT (fcti (sons g) i) -> hasCycle' RelT g.
    Proof.
      intros [g' H1 H2].
      apply (hasCycle'_intro H1).
      apply (GinG'_trans _ H2).
      apply GinG'_sons_in_Graph, is_Graph_in_Graph_Gene_dir.
      apply (Geq_refl _).
    Qed.

    Lemma hasCycle_hasCycle'(T: Set)(RelT: relation T)(Req: Equivalence RelT)(g: Graph T):
      hasCycle RelT g -> hasCycle' RelT g.
    Proof.
      intros H.
      induction H as [g H |g i H IH].
      - apply (hasCycle'_intro H).
        apply is_Graph_in_Graph_Gene_dir.
        apply (Geq_refl _).
      - apply (hasCycle'_sons _ _ _ IH).
    Qed.

    Add Parametric Morphism (T: Set)(RelT: relation T)(Req: Equivalence RelT) :
      (is_cycle RelT) with signature (Geq RelT) ==> (impl)
    as is_cycleM.
    Proof.
      intros g1 g2 H1 H2.
      apply (Graph_in_GraphM _ H1), (Graph_in_GraphM2 _ H1), H2.
    Qed.

    Lemma hasCycle'_hasCycle(T: Set)(RelT: relation T)(Req: Equivalence RelT)(g: Graph T):
      hasCycle' RelT g -> hasCycle RelT g.
    Proof.
      intros [g' H1 H2].
      induction H2 as [g H2 |g i H2 IH].
      - apply hasCycle_dir.
        rewrite <- H2.
        apply H1.
      - apply (hasCycle_indir _ i IH).
    Qed.

End hasCycle'.


(* This really should be called ChainCompletePoset, but that's a mouthful. *)

Require Import Tactics.
Require Import Axioms.
Require Import Relation.

Definition is_chain {T : Type} (R : relation T) (P : T -> Prop) : Prop
  :=
  forall x y,
    P x
    -> P y
    -> R x y \/ R y x.

(* chain-complete poset *)
Record ccp : Type :=
mk_lat
  { lat_car : Type;
    lat_le : lat_car -> lat_car -> Prop;
    lat_join : forall (P : lat_car -> Prop), is_chain lat_le P -> lat_car;

    lat_le_refl : forall x, lat_le x x;

    lat_le_trans :
      forall x y z,
        lat_le x y
        -> lat_le y z
        -> lat_le x z;

    lat_le_antisymm :
      forall x y,
        lat_le x y
        -> lat_le y x
        -> x = y;

    lat_join_ub :
      forall (P : lat_car -> Prop) h x,
        P x
        -> lat_le x (lat_join P h);

    lat_join_least :
      forall (P : lat_car -> Prop) h x,
        (forall y, P y -> lat_le y x)
        -> lat_le (lat_join P h) x
  }.

Lemma lat_le_refl' :
  forall L (x y : lat_car L),
    x = y
    -> lat_le L x y.
Proof.
intros L x y H.
subst y.
apply lat_le_refl.
Qed.

Lemma empty_chain :
  forall L, is_chain (lat_le L) (fun _ => False).
Proof.
intros L.
intros x y H.
destruct H.
Qed.

Definition lat_bot (L : ccp) : lat_car L
  :=
  lat_join L (fun _ => False) (empty_chain L).

Lemma lat_bot_least :
  forall L x,
    lat_le L (lat_bot L) x.
Proof.
intros L x.
apply lat_join_least.
intros y H.
destruct H.
Qed.

Definition impl {S T : Type} (Q : S -> S -> Prop) (R : T -> T -> Prop) (F : S -> T)
  : Prop
  :=
  forall A B, Q A B -> R (F A) (F B).

Lemma impl_compose :
  forall S T U (P : S -> S -> Prop) (Q : T -> T -> Prop) (R : U -> U -> Prop)
    (F : S -> T) (G : T -> U),
      impl P Q F
      -> impl Q R G
      -> impl P R (fun X => G (F X)).
Proof.
intros S T U P Q R F G HmonoF HmonoG.
intros x y Hxy.
auto.
Qed.

(* Proof technique borrowed from Proving Fixed Points, by Herve Grall. *)

Inductive iterand (L : ccp) (F : lat_car L -> lat_car L) : lat_car L -> Prop :=
| iterand_intro :
    forall C (h : is_chain (lat_le L) C),
      (forall x,
         C x
         -> iterand L F x)
      -> iterand L F (F (lat_join L C h)).

Lemma iterand_chain :
  forall L F,
    impl (lat_le L) (lat_le L) F
    -> is_chain (lat_le L) (iterand L F).
Proof.
intros L F Hmono.
intros x y Hx Hy.
revert y Hy.
induct Hx.
intros C1 Hchain1 _ IH y Hy.
invertc Hy.
intros C2 Hchain2 HC2 <-.
so (excluded_middle (exists x, C1 x /\ forall y, C2 y -> lat_le L y x)) as [Hyes | Hno].
  {
  destruct Hyes as (x & Hx & Hall).
  right.
  apply Hmono.
  apply lat_join_least.
  intros y Hy.
  apply (lat_le_trans _ _ x).
    {
    apply Hall; auto.
    }

    {
    apply lat_join_ub; auto.
    }
  }
assert (forall x, C1 x -> exists y, C2 y /\ ~ lat_le L y x) as Hyes.
  {
  intros x Hx.
  apply proof_by_contradiction.
  contradict Hno.
  exists x.
  split; auto.
  intros y Hy.
  so (excluded_middle (lat_le L y x)) as [Hyx | Hnyx]; auto.
  destruct Hno.
  exists y.
  auto.
  }
left.
apply Hmono.
apply lat_join_least.
intros x Hx.
so (Hyes x Hx) as (y & Hy & Hnyx).
so (IH x Hx y (HC2 y Hy)) as [Hxy | Hyx].
2:{
  contradiction.
  }
apply (lat_le_trans _ _ y); auto.
apply lat_join_ub; auto.
Qed.

Lemma iterand_least :
  forall L F x y,
    impl (lat_le L) (lat_le L) F
    -> lat_le L (F x) x
    -> iterand L F y
    -> lat_le L y x.
Proof.
intros L F x y Hmono Hprefix Hy.
induct Hy.
intros C Hchain _ IH.
apply (lat_le_trans _ _ (F x)); auto.
apply Hmono.
apply lat_join_least.
intros y Hy.
apply IH; auto.
Qed.

Definition lfp L F (h : impl (lat_le L) (lat_le L) F) : lat_car L
  :=
  lat_join L (iterand L F) (iterand_chain L F h).

Lemma lfp_least :
  forall L F x (h : impl (lat_le L) (lat_le L) F),
    lat_le L (F x) x
    -> lat_le L (lfp L F h) x.
Proof.
intros L F x Hmono Hprefix.
apply lat_join_least.
intros y Hy.
eapply iterand_least; eauto.
Qed.

Lemma lfp_prefix :
  forall L F (h : impl (lat_le L) (lat_le L) F),
    lat_le L (F (lfp L F h)) (lfp L F h).
Proof.
intros L F h.
apply lat_join_ub.
apply iterand_intro.
auto.
Qed.

Lemma lfp_postfix :
  forall L F (h : impl (lat_le L) (lat_le L) F),
    lat_le L (lfp L F h) (F (lfp L F h)).
Proof.
intros L F h.
apply lfp_least.
apply h.
apply lfp_prefix.
Qed.

Lemma lfp_fix :
  forall L F (h : impl (lat_le L) (lat_le L) F),
    lfp L F h = F (lfp L F h).
Proof.
intros L F h.
apply lat_le_antisymm; auto using lfp_prefix, lfp_postfix.
Qed.

Lemma fixpoint_iteration :
  forall L (F : lat_car L -> lat_car L) (P : lat_car L -> Prop)
    (h : impl (lat_le L) (lat_le L) F),
      (forall x, P x -> P (F x))
      -> (forall C (h : is_chain (lat_le L) C),
            (forall x, C x -> P x)
            -> P (lat_join L C h))
      -> P (lfp L F h).
Proof.
intros L F P Hmono Hinc Hjoin.
rewrite -> lfp_fix.
assert (iterand L F (F (lfp L F Hmono))) as H.
  {
  apply iterand_intro; auto.
  }
set (x := F (lfp L F Hmono)) in H |- *.
clearbody x.
induct H.
intros C Hchain _ IH.
apply Hinc.
apply Hjoin; auto.
Qed.

Definition map_set {T : Type} (f : T -> T) (P : T -> Prop) : T -> Prop
  :=
  fun x => exists y, x = f y /\ P y.

Lemma map_chain :
  forall T (R : relation T) (f : T -> T) (P : T -> Prop),
    impl R R f
    -> is_chain R P
    -> is_chain R (map_set f P).
Proof.
intros T R f P Hmono Hchain.
intros x y Hx Hy.
destruct Hx as (x' & -> & Hx).
destruct Hy as (y' & -> & Hy).
so (Hchain x' y' Hx Hy) as [Hxy | Hyx].
  {
  left.
  apply Hmono; auto.
  }

  {
  right.
  apply Hmono; auto.
  }
Qed.

Definition chain_continuous (L : ccp) (F : lat_car L -> lat_car L)
  : Prop
  :=
  exists (Hmono : impl (lat_le L) (lat_le L) F),
    forall C (h : is_chain (lat_le L) C),
      F (lat_join L C h) = lat_join L (map_set F C) (map_chain _#4 Hmono h).

Lemma chain_continuous_impl_monotone :
  forall L F,
    chain_continuous L F
    -> impl (lat_le L) (lat_le L) F.
Proof.
intros L F H.
destruct H; auto.
Qed.

Lemma vanish :
  forall L (F G : lat_car L -> lat_car L)
    (HF : chain_continuous L F)
    (HG : impl (lat_le L) (lat_le L) G),
      (forall x, F (G (F x)) = G (F x))
      -> lfp L (fun x => G (F x)) (impl_compose _#8 (chain_continuous_impl_monotone _ _ HF) HG)
         =
         lfp L G HG.
Proof.
intros L F G HcontF HmonoG Hequation.
destruct HcontF as (HmonoF & HcontF).
match goal with
| |- lfp _ _ ?X = _ => set (HmonoGF := X)
end.
clearbody HmonoGF.
apply (lat_le_antisymm L).
2:{
  apply lfp_least.
  rewrite -> lfp_fix at 1; auto.
  rewrite <- Hequation.
  rewrite <- (lfp_fix L (fun X => G (F X))).
  rewrite <- (lfp_fix L (fun X => G (F X))).
  apply lat_le_refl.
  }
apply lfp_least.
rewrite -> lfp_fix at 2; auto.
apply HmonoG.
exploit (fixpoint_iteration _ G (fun x => x = F x) HmonoG) as H; auto.
  {
  intros x Heq.
  rewrite -> Heq at 2.
  rewrite -> Hequation.
  rewrite <- Heq.
  reflexivity.
  }

  {
  intros C Hchain IH.
  rewrite -> HcontF.
  (* with the dependent types, it's easier to go with inequalities *)
  apply lat_le_antisymm.
    {
    apply lat_join_least.
    intros x Hx.
    apply lat_join_ub.
    exists x; auto.
    }

    {
    apply lat_join_least.
    intros x Hx.
    apply lat_join_ub.
    destruct Hx as (x' & -> & Hx).
    rewrite <- IH; auto.
    }
  }
cbn in H.
rewrite -> H at 2.
apply lat_le_refl.
Qed.

Lemma vanish' :
  forall L (F G : lat_car L -> lat_car L) gf g,
    chain_continuous L F
    -> impl (lat_le L) (lat_le L) G
    -> (forall x, F (G (F x)) = G (F x))
    -> lat_le L (G (F gf)) gf
    -> (forall x, lat_le L (G (F x)) x -> lat_le L gf x)
    -> lat_le L (G g) g
    -> (forall x, lat_le L (G x) x -> lat_le L g x)
    -> gf = g.
Proof.
intros L F G gf g HcontF HmonoG Hequation Hprefixgf Hleastgf Hprefixg Hleastg.
transitivity (lfp L (fun x => G (F x)) (impl_compose _#8 (chain_continuous_impl_monotone _ _ HcontF) HmonoG)).
  {
  apply lat_le_antisymm.
    {
    apply Hleastgf.
    apply (lfp_prefix L (fun x => G (F x))).
    }

    {
    apply lfp_least.
    auto.
    }
  }
transitivity (lfp L G HmonoG).
  {
  apply vanish; auto.
  }
apply lat_le_antisymm.
  {
  apply lfp_least; auto.
  }

  {
  apply Hleastg.
  apply lfp_prefix.
  }
Qed.


From FormalSystems Require Export Imp.Syntax.
From FormalSystems Require Import Imp.Denotational.

Inductive AEval : AExp -> State -> nat -> Prop :=
    | EvalAConst :
        forall (n : nat) (s : State), AEval (AConst n) s n
    | EvalVar :
        forall (v : Loc) (s : State), AEval (Var v) s (s v)
    | EvalABinOp :
        forall (f : nat -> nat -> nat)
               (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 ->
            AEval (ABinOp f a1 a2) s (f n1 n2).

#[global] Hint Constructors AEval : core.

Lemma AEval_det :
  forall {a : AExp} {s : State} {n m : nat},
    AEval a s n -> AEval a s m -> n = m.
Proof.
  intros a s n m H. revert m.
  induction H; inversion 1; subst; clear H.
    1-2: reflexivity.
    rewrite (IHAEval1 _ H7), (IHAEval2 _ H8). reflexivity.
Qed.

#[global] Hint Resolve in_or_app : core.

Lemma AEval_acompatible :
  forall {a : AExp} {s1 : State} {n : nat},
    AEval a s1 n -> forall {s2 : State},
      acompatible a s1 s2 ->
        AEval a s2 n.
Proof.
  unfold acompatible.
  induction 1; cbn in *; intros; try rewrite H; auto 6.
Qed.

Lemma AEval_acompatible_det :
  forall {a : AExp} {s1 : State} {n1 : nat},
    AEval a s1 n1 ->
    forall {s2 : State} {n2 : nat},
      AEval a s2 n2 ->
      (forall x : Loc, In x (loca a) -> s1 x = s2 x) ->
        n1 = n2.
Proof.
  induction 1; cbn; intros; auto.
    inv H.
    inv H.
    inv H1. erewrite IHAEval1, IHAEval2; eauto.
Qed.

Inductive BEval : BExp -> State -> bool -> Prop :=
    | EvalBConst :
        forall (s : State) (b : bool), BEval (BConst b) s b
    | BEval_BRelOp :
        forall (f : nat -> nat -> bool)
               (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 ->
            BEval (BRelOp f a1 a2) s (f n1 n2)
    | EvalNot :
        forall (e : BExp) (s : State) (b : bool),
          BEval e s b -> BEval (Not e) s (negb b)
    | BEval_BBinOp :
        forall (f : bool -> bool -> bool)
               (e1 e2 : BExp) (s : State) (b1 b2 : bool),
          BEval e1 s b1 -> BEval e2 s b2 ->
            BEval (BBinOp f e1 e2) s (f b1 b2).

#[global] Hint Constructors BEval : core.

Lemma BEval_det :
  forall {e : BExp} {s : State} {b1 : bool},
    BEval e s b1 -> forall {b2 : bool}, BEval e s b2 -> b1 = b2.
Proof.
  induction 1; intros.
    inv H.
    inv H1. rewrite (AEval_det H H7), (AEval_det H0 H8). reflexivity.
    inv H0. rewrite (IHBEval _ H2). reflexivity.
    inv H1. rewrite (IHBEval1 _ H7), (IHBEval2 _ H8). reflexivity.
Qed.

#[global] Hint Resolve AEval_acompatible : core.
#[global] Hint Unfold acompatible : core.

Lemma BEval_bcompatible :
  forall {e : BExp} {s1 : State} {b : bool},
    BEval e s1 b -> forall {s2 : State},
      bcompatible e s1 s2 -> BEval e s2 b.
Proof.
  unfold bcompatible.
  induction 1; cbn in *; intros; constructor; eauto 6.
Qed.

Lemma BEval_bcompatible_det :
  forall {e : BExp} {s1 : State} {b1 : bool},
    BEval e s1 b1 -> forall {s2 : State} {b2 : bool},
    BEval e s2 b2 ->
      bcompatible e s1 s2 -> b1 = b2.
Proof.
  intros.
  assert (BEval e s2 b1).
    eapply BEval_bcompatible; eauto.
  eapply BEval_det; eauto.
Qed.

Inductive CEval : Com -> State -> State -> Prop :=
    | EvalSkip :
        forall s : State, CEval Skip s s
    | EvalAsgn :
        forall (v : Loc) (a : AExp) (s : State) (n : nat),
          AEval a s n -> CEval (Asgn v a) s (changeState s v n)
    | EvalSeq :
        forall (c1 c2 : Com) (s1 s2 s3 : State),
          CEval c1 s1 s2 -> CEval c2 s2 s3 -> CEval (Seq c1 c2) s1 s3
    | EvalIfFalse :
        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),
          BEval b s1 false -> CEval c2 s1 s2 -> CEval (If b c1 c2) s1 s2
    | EvalIfTrue :
        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),
          BEval b s1 true -> CEval c1 s1 s2 -> CEval (If b c1 c2) s1 s2
    | EvalWhileFalse :
        forall (b : BExp) (c : Com) (s : State),
          BEval b s false -> CEval (While b c) s s
    | EvalWhileTrue :
        forall (b : BExp) (c : Com) (s1 s2 s3 : State),
          BEval b s1 true ->
          CEval c s1 s2 -> CEval (While b c) s2 s3 ->
            CEval (While b c) s1 s3.

#[global] Hint Constructors CEval : core.

Example while_true_do_skip :
  forall s1 s2 : State,
    ~ CEval (While (BConst true) Skip) s1 s2.
Proof.
  intros s1 s2 H.
  remember (While (BConst true) Skip) as w. revert Heqw.
  induction H; intros; inv Heqw. inv H.
Qed.

#[global] Hint Rewrite @AEval_det : core.
#[global] Hint Resolve AEval_det BEval_det : core.

Lemma CEval_det :
  forall (c : Com) (s s1 : State),
    CEval c s s1 -> forall s2 : State, CEval c s s2 -> s1 = s2.
Proof.
  induction 1; intros;
  match goal with
      | H : CEval ?c _ _ |- _ => is_var c + inv H
  end;
  repeat match goal with
      | IH : forall _, CEval _ _ _ -> _, H : CEval _ _ _ |- _ =>
          let H' := fresh "H" in
            assert (H' := IH _ H); clear H; rename H' into H; subst
      | H : BEval ?b ?s _, H' : BEval ?b ?s _ |- _ =>
          let H'' := fresh "H" in
            assert (H'' := BEval_det H H'); clear H H'
  end; eauto; try congruence.
Qed.

(** * Equivalence of big step and denotational semantics *)

Lemma AEval_aeval :
  forall {a : AExp} {s : State} {n : nat},
    AEval a s n -> aeval s a = n.
Proof.
  induction 1; cbn; rewrite ?IHAEval1, ?IHAEval2; reflexivity.
Qed.

Lemma aeval_AEval :
  forall {a : AExp} {s : State} {n : nat},
    aeval s a = n -> AEval a s n.
Proof.
  induction a; cbn; intros; rewrite <- H; auto.
Qed.

Lemma BEval_beval :
  forall {e : BExp} {s : State} {b : bool},
    BEval e s b -> beval s e = b.
Proof.
  induction 1; cbn.
    reflexivity.
    rewrite (AEval_aeval H), (AEval_aeval H0). reflexivity.
    rewrite IHBEval. reflexivity.
    rewrite IHBEval1, IHBEval2. reflexivity.
Qed.

Lemma beval_BEval :
  forall {e : BExp} {s : State} {b : bool},
    beval s e = b -> BEval e s b.
Proof.
  induction e; cbn; intros; subst; auto.
    constructor; apply aeval_AEval; reflexivity.
Qed.

#[global] Hint Immediate aeval_AEval beval_BEval : core.

Lemma ceval_CEval :
  forall (n : nat) (c : Com) (s1 s2 : State),
    ceval n c s1 = Some s2 -> CEval c s1 s2.
Proof.
  intros n c s1. functional induction ceval n c s1; intros; inv H; eauto.
Qed.

Lemma CEval_ceval :
  forall (c : Com) (s1 s2 : State),
    CEval c s1 s2 -> exists n : nat, ceval n c s1 = Some s2.
Proof.
  induction 1.
    exists 1. cbn. reflexivity.
    exists 1. cbn. do 2 f_equal. apply AEval_aeval. assumption.
    destruct IHCEval1 as [n1 IH1], IHCEval2 as [n2 IH2].
      exists (S (n1 + n2)). (* Should be S (max n1 n2) *)
      cbn. rewrite (ceval_plus n1 n2 _ _ _ IH1), plus_comm.
        apply ceval_plus. assumption.
    destruct IHCEval as [n IH]. exists (S n). cbn.
      apply BEval_beval in H. rewrite H. assumption.
    destruct IHCEval as [n IH]. exists (S n). cbn.
      apply BEval_beval in H. rewrite H. assumption.
    exists 1. cbn. apply BEval_beval in H. rewrite H. reflexivity.
    destruct IHCEval1 as [n1 IH1], IHCEval2 as [n2 IH2].
      exists (S (n1 + n2)). cbn. (* Should be S (max n1 n2) *)
      apply BEval_beval in H. rewrite H.
      rewrite (ceval_plus _ _ _ _ _ IH1), plus_comm.
      apply ceval_plus. assumption.
Qed.


Require Import SpecCert.Interval.Interval_ind.
Require Import SpecCert.Interval.Interval_func.

Definition is_inside_interval (x:nat) (i:Interval) :=
  let b := lower_bound i in
  let e := upper_bound i in
    b <= x /\ x <= e.

Definition is_included_in(i1 i2:Interval) :=
  let b1 := lower_bound i1 in
  let b2 := lower_bound i2 in
  let e2 := upper_bound i2 in
  let e1 := upper_bound i1 in
    b2 <= b1 /\ e1 <= e2.

Definition disjoint (i1 i2:Interval) :=
  let b1 := lower_bound i1 in
  let b2 := lower_bound i2 in
  let e2 := upper_bound i2 in
  let e1 := upper_bound i1 in
    e1 < b2 /\ e2 < b1.