(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below    *)
Require Import BuiltIn.
Require BuiltIn.

(* Why3 assumption *)
Definition unit := unit.

(* Why3 assumption *)
Inductive term :=
  | S : term
  | K : term
  | App : term -> term -> term.
Axiom term_WhyType : WhyType term.
Existing Instance term_WhyType.

(* Why3 assumption *)
Fixpoint is_value (t:term) {struct t}: Prop :=
  match t with
  | (K|S) => True
  | ((App K v)|(App S v)) => (is_value v)
  | (App (App S v1) v2) => (is_value v1) /\ (is_value v2)
  | _ => False
  end.

(* Why3 assumption *)
Inductive context :=
  | Hole : context
  | Left : context -> term -> context
  | Right : term -> context -> context.
Axiom context_WhyType : WhyType context.
Existing Instance context_WhyType.

(* Why3 assumption *)
Fixpoint is_context (c:context) {struct c}: Prop :=
  match c with
  | Hole => True
  | (Left c1 _) => (is_context c1)
  | (Right v c1) => (is_value v) /\ (is_context c1)
  end.

(* Why3 assumption *)
Fixpoint subst (c:context) (t:term) {struct c}: term :=
  match c with
  | Hole => t
  | (Left c1 t2) => (App (subst c1 t) t2)
  | (Right v1 c2) => (App v1 (subst c2 t))
  end.

(* Why3 assumption *)
Inductive infix_mnmngt: term -> term -> Prop :=
  | red_K : forall (c:context), (is_context c) -> forall (v1:term) (v2:term),
      (is_value v1) -> ((is_value v2) -> (infix_mnmngt (subst c (App (App K
      v1) v2)) (subst c v1)))
  | red_S : forall (c:context), (is_context c) -> forall (v1:term) (v2:term)
      (v3:term), (is_value v1) -> ((is_value v2) -> ((is_value v3) ->
      (infix_mnmngt (subst c (App (App (App S v1) v2) v3)) (subst c
      (App (App v1 v3) (App v2 v3)))))).

Axiom red_left : forall (t1:term) (t2:term) (t:term), (infix_mnmngt t1 t2) ->
  (infix_mnmngt (App t1 t) (App t2 t)).

Axiom red_right : forall (v:term) (t1:term) (t2:term), (is_value v) ->
  ((infix_mnmngt t1 t2) -> (infix_mnmngt (App v t1) (App v t2))).

(* Why3 assumption *)
Inductive relTR: term -> term -> Prop :=
  | BaseTransRefl : forall (x:term), (relTR x x)
  | StepTransRefl : forall (x:term) (y:term) (z:term), (relTR x y) ->
      ((infix_mnmngt y z) -> (relTR x z)).

Axiom relTR_transitive : forall (x:term) (y:term) (z:term), (relTR x y) ->
  ((relTR y z) -> (relTR x z)).

Axiom red_star_left : forall (t1:term) (t2:term) (t:term), (relTR t1 t2) ->
  (relTR (App t1 t) (App t2 t)).

Axiom red_star_right : forall (v:term) (t1:term) (t2:term), (is_value v) ->
  ((relTR t1 t2) -> (relTR (App v t1) (App v t2))).

Hint Constructors infix_mnmngt.
Require Import Why3.
Ltac ae := why3 "Alt-Ergo,0.99.1," timelimit 5; admit.

(* Why3 goal *)
Theorem reducible_or_value : forall (t:term), (exists t':term, (infix_mnmngt
  t t')) \/ (is_value t).
(* Why3 intros t. *)
induction t; intuition.
right; simpl; auto.
right; simpl; auto.
left.
destruct H as (t1',h1).
exists (App t1' t2); intuition. ae.
left.
destruct H as (t1',h1).
exists (App t1' t2); intuition. ae.
left.
destruct H0 as (t2',h2).
exists (App t1 t2'); intuition. ae.
(* is_value t1 && is_value t2 *)
destruct t1; intuition.
destruct t1_1; intuition.
simpl in H.
right; red; intuition.
simpl in H.
left; intuition.
exists t1_2; intuition.
apply (red_K Hole); auto. ae.
simpl in H.
destruct t1_1_1; intuition.
left.
rename t1_1_2 into v1. rename t1_2 into v2. rename t2 into v3.
exists (App (App v1 v3) (App v2 v3)); intuition.
apply (red_S Hole); auto.
ae.
Admitted.


Require Import Classical.
Require Import List.
From mathcomp Require Import ssreflect seq.

Class Sem (CFG : Type) (RCFG : Type) :=
  {
  rule : seq (prod CFG RCFG) -> (prod CFG RCFG) -> Prop
  }.

Definition Spec (PARAM : Type) (CFG : Type) (RCFG : Type)
           (param : PARAM) :=
  CFG -> (RCFG -> Prop) -> Prop.

Inductive deriv {CFG} {RCFG} {sem : Sem CFG RCFG}
  : (prod CFG RCFG)->Prop :=
  Der:
    forall c r lst,
      rule lst (c, r) ->
      (forall i p, nth_error lst i = Some p -> deriv p) ->
      deriv (c, r).

(* definition of "res" inlined into definition of "infer" *)
Inductive infer {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}
          (param : PARAM) (phi : Spec PARAM CFG RCFG param)
  : (prod CFG RCFG) -> Prop :=
  Inf:
    forall c r crs,
      rule crs (c, r) ->
      (forall i p,
          nth_error crs i = Some p ->
          (((~(exists P, phi (fst p) P)) /\ infer param phi p) \/
           (exists P, phi (fst p) P /\ P (snd p)))
      ) ->
      infer param phi (c, r).

(* Perhaps due to the positioning of the subterm "infer param phi p",
   the generated ind principle is unusable.
   We prove a custome induction principle for infer. *)
Fixpoint infer_ind'
         (PARAM CFG RCFG: Type)
         (sem: Sem CFG RCFG)
         (param: PARAM)
         (phi: Spec PARAM CFG RCFG param)
         (P: (prod CFG RCFG) -> Prop)
         (eInf: forall c r crs,
             rule crs (c, r) ->
             (forall i p',
                 nth_error crs i = Some p' ->
                 (((~(exists P', phi (fst p') P')) /\ infer param phi p') \/
                  (exists P', phi (fst p') P' /\ P' (snd p')))) ->
             (forall i p', nth_error crs i = Some p' ->
                          (((~(exists P', phi (fst p') P')) /\ P p') \/
                           (exists P', phi (fst p') P' /\ P' (snd p')))
             ) ->
             P (c, r)
         )
         (p: prod CFG RCFG)
         (e: infer param phi p)
  :
    P p.
  refine (match e with
          | Inf c r crs H_rule H' => _
          end).
  apply eInf with (crs:=crs)=>//.
  move=> i p' H_ip'.
  move: H'=>/(_ i p' H_ip')=> H'.
  elim H'=> H'_case.
  - left. case H'_case =>[H_ne H_infer]. apply: conj=>//.
    apply infer_ind' with
        (PARAM:=PARAM) (sem:=sem) (param:=param) (phi:=phi)=>//.
  - right=>//.
Defined.

Definition verif {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}
           (param : PARAM)
  : (Spec PARAM CFG RCFG param) -> Prop :=
  (fun phi =>
     (forall c r P,
         infer param phi (c, r) -> phi c P -> P r)).

Definition valid {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}
           (param : PARAM)
  : (Spec PARAM CFG RCFG param) -> Prop :=
  (fun phi =>
     (forall c r P,
         deriv (c, r) -> phi c P -> P r)).

Lemma deriv_impl_infer {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}:
  forall (param: PARAM) (phi: Spec PARAM CFG RCFG param) c r,
    verif param phi -> deriv (c, r) -> infer param phi (c, r).
Proof.
  move=> param phi c r H_ver.
  move En: (c, r)=> p0 H_deriv.
  move: H_deriv c r En.
  elim.
  move=> c r lst H_rule H_der_i IH c0 r0 H_eq.
  apply: Inf. apply: H_rule.
  move=> i p' H_ip'.
  move: IH =>/(_ i p' H_ip' (fst p') (snd p')).
  rewrite -surjective_pairing=>/(_ (eq_refl _))=>IH.
  have H_or: (exists P, phi (fst p') P) \/ ~(exists P, phi (fst p') P)
    by apply: classic.
  case H_or=> H_exnex.
  - right.
    case: H_exnex => [P H_phicP].
    rewrite /verif in H_ver.
    exists P=>/=. apply: conj=>//.
    move: H_ver=>/(_ (fst p') (snd p') P).
    rewrite -surjective_pairing.
    move=> H_ver; apply: H_ver=>//=.
  - left. apply: conj=>//.
Qed.

Theorem soundness {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}:
  forall (param: PARAM) phi, verif param phi -> valid param phi.
Proof.
  move=> param phi H_ver.
  have H'_ver: verif param phi by done.
  rewrite /verif in H'_ver. rewrite /valid.
  move=> c r P H_der H_phic.
  have H_inf: infer param phi (c, r) by apply: deriv_impl_infer=>//.
  move: H'_ver=> /(_ c r P H_inf H_phic)=>//.
Qed.

Inductive phi_valid {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG} (param: PARAM):
  (Spec PARAM CFG RCFG param) :=
  PV c: phi_valid param c (fun r => deriv (c, r)).

Lemma phi_valid_infer_deriv {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}:
  forall (param: PARAM) c r,
    infer param (phi_valid param) (c, r) -> deriv (c, r).
Proof.
  move=> param c r.
  move En: (c, r)=> p.
  move En': (phi_valid param)=> phiprm.
  move=> H_infer. move: H_infer c r En.
  elim /infer_ind'.
  move=> c r crs H_rule H_i IH c0 r0 H_eq.
  apply: Der. apply: H_rule.
  move=> i p0 H_ip0.
  move: IH=>/(_ i p0 H_ip0)=> IH.
  case IH=> [H_nex | H_ex].
  - case H_nex=> [H_ne H_inf].
    move: H_inf=>/(_ (fst p0) (snd p0)).
    rewrite -surjective_pairing=>/(_ (eq_refl _))=>//.
  - case H_ex=> [P' [H_phiprm H']].
    rewrite <- En' in H_phiprm.
    inversion H_phiprm; subst.
    rewrite -surjective_pairing in H'=>//.
Qed.

Lemma phi_valid_verifiable {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}:
  forall (param: PARAM), verif param (phi_valid param).
Proof.
  move=> param.
  rewrite /verif.
  move=> c r P H_infer H_phi_v.
  inversion H_phi_v; subst.
  apply phi_valid_infer_deriv with (param0:=param)=>//.
Qed.

Definition spec_le {PARAM} {CFG} {RCFG}
           (param: PARAM) (phi phi' : Spec PARAM CFG RCFG param) : Prop
  :=
  (forall c P, (phi c P ->
                (exists (P': RCFG->Prop),
                    (forall r, P' r -> P r) /\ phi' c P'))).

Lemma valid_phi_le_phi_valid {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG} :
  forall (param: PARAM) phi,
    valid param phi -> spec_le param phi (phi_valid param).
Proof.
  rewrite /valid /spec_le.
  move=> param phi H_all c P H_phic.
  exists (fun r => deriv (c, r)).
  apply: conj. move=> r H_der.
  move: H_all=> /(_ c r P H_der H_phic)=>//.
  by apply: PV.
Qed.

Theorem completeness {PARAM} {CFG} {RCFG} {sem : Sem CFG RCFG}:
  forall (param: PARAM) (phi : Spec PARAM CFG RCFG param),
    valid param phi ->
    (exists phi', valid param phi' /\
                  spec_le param phi phi' /\
                  verif param phi').
Proof.
  move=> param phi H_valid.
  exists (phi_valid param).
  apply: conj.
  rewrite /valid.
  move=> c r P H_der H_phi_valid.
  inversion H_phi_valid; subst=>//.
  apply: conj;
    [apply: valid_phi_le_phi_valid | apply: phi_valid_verifiable]=>//.
Qed.


Require Import Coq.Vectors.Vector.
Require Import Coq.ZArith.ZArith.

Require Import UkModulo.Notations.Vector.

Open Scope Z.
Open Scope vector_scope.

Definition digit : Set := {n : Z | 0 <= n <= 9}.

Definition digit_value (d : digit) : Z := proj1_sig d.

Definition t : Set := Vector.t digit 14.

Definition as_vector_z (d : t) : {r : Vector.t Z 14 | forall m : Fin.t 14, r[@m] = digit_value d[@m]}.
  refine (exist _ (map digit_value d) _).
  intros m; now apply VectorSpec.nth_map.
Defined.

Section Digits.

  Definition digit_check (n : Z) : Prop := 0 <= n <= 9.

  Ltac digit_proof := split; compute; discriminate.

  Lemma digit_0 : 0 <= 0 <= 9. digit_proof. Qed.
  Lemma digit_1 : 0 <= 1 <= 9. digit_proof. Qed.
  Lemma digit_2 : 0 <= 2 <= 9. digit_proof. Qed.
  Lemma digit_3 : 0 <= 3 <= 9. digit_proof. Qed.
  Lemma digit_4 : 0 <= 4 <= 9. digit_proof. Qed.
  Lemma digit_5 : 0 <= 5 <= 9. digit_proof. Qed.
  Lemma digit_6 : 0 <= 6 <= 9. digit_proof. Qed.
  Lemma digit_7 : 0 <= 7 <= 9. digit_proof. Qed.
  Lemma digit_8 : 0 <= 8 <= 9. digit_proof. Qed.
  Lemma digit_9 : 0 <= 9 <= 9. digit_proof. Qed.

  Definition _0 : digit := exist digit_check 0 digit_0.
  Definition _1 : digit := exist digit_check 1 digit_1.
  Definition _2 : digit := exist digit_check 2 digit_2.
  Definition _3 : digit := exist digit_check 3 digit_3.
  Definition _4 : digit := exist digit_check 4 digit_4.
  Definition _5 : digit := exist digit_check 5 digit_5.
  Definition _6 : digit := exist digit_check 6 digit_6.
  Definition _7 : digit := exist digit_check 7 digit_7.
  Definition _8 : digit := exist digit_check 8 digit_8.
  Definition _9 : digit := exist digit_check 9 digit_9.

End Digits.

Section Proofs.

  Theorem digit_value_correct :
       digit_value _0 = 0
    /\ digit_value _1 = 1
    /\ digit_value _2 = 2
    /\ digit_value _3 = 3
    /\ digit_value _4 = 4
    /\ digit_value _5 = 5
    /\ digit_value _6 = 6
    /\ digit_value _7 = 7
    /\ digit_value _8 = 8
    /\ digit_value _9 = 9.
  Proof.
    repeat (split; auto).
  Qed.

  Definition a : t :=
    [ _0; _8; _9; _9; _9; _9;
      _6; _6; _3; _7; _4; _9; _5; _8 ].

End Proofs.


(**************************************************************)
(* FSetDecide.v                                               *)
(*                                                            *)
(* Author: Aaron Bohannon                                     *)
(**************************************************************)

(** This file implements a decision procedure for a certain
    class of propositions involving finite sets.  *)

Require Import FSets.

Module Decide (Import M : S).

(** * Overview
    This functor defines the tactic [fsetdec], which will
    solve any valid goal of the form
<<
    forall s1 ... sn,
    forall x1 ... xm,
    P1 -> ... -> Pk -> P
>>
    where [P]'s are defined by the grammar:
<<

P ::=
| Q
| Empty F
| Subset F F'
| Equal F F'

Q ::=
| E.eq X X'
| In X F
| Q /\ Q'
| Q \/ Q'
| Q -> Q'
| Q <-> Q'
| ~ Q
| True
| False

F ::=
| S
| empty
| singleton X
| add X F
| remove X F
| union F F'
| inter F F'
| diff F F'

X ::= x1 | ... | xm
S ::= s1 | ... | sn

>>

The tactic will also work on some goals that vary slightly from
the above form:
- The variables and hypotheses may be mixed in any order and may
  have already been introduced into the context.  Moreover,
  there may be additional, unrelated hypotheses mixed in (these
  will be ignored).
- A conjunction of hypotheses will be handled as easily as
  separate hypotheses, i.e., [P1 /\ P2 -> P] can be solved iff
  [P1 -> P2 -> P] can be solved.
- [fsetdec] should solve any goal if the FSet-related hypotheses
  are contradictory.
- [fsetdec] will first perform any necessary zeta and beta
  reductions and will invoke [subst] to eliminate any Coq
  equalities between finite sets or their elements.
- If [E.eq] is convertible with Coq's equality, it will not
  matter which one is used in the hypotheses or conclusion.
- The tactic can solve goals where the finite sets or set
  elements are expressed by Coq terms that are more complicated
  than variables.  However, non-local definitions are not
  expanded, and Coq equalities between non-variable terms are
  not used.  For example, this goal will be solved:
<<
    forall (f : t -> t),
    forall (g : elt -> elt),
    forall (s1 s2 : t),
    forall (x1 x2 : elt),
    Equal s1 (f s2) ->
    E.eq x1 (g (g x2)) ->
    In x1 s1 ->
    In (g (g x2)) (f s2)
>>
  This one will not be solved:
<<
    forall (f : t -> t),
    forall (g : elt -> elt),
    forall (s1 s2 : t),
    forall (x1 x2 : elt),
    Equal s1 (f s2) ->
    E.eq x1 (g x2) ->
    In x1 s1 ->
    g x2 = g (g x2) ->
    In (g (g x2)) (f s2)
>>
*)

  (** * Facts and Tactics for Propositional Logic
      These lemmas and tactics are in a module so that they do
      not affect the namespace if you import the enclosing
      module [Decide]. *)
  Module FSetLogicalFacts.
    Require Export Decidable.
    Require Export Setoid.

    (** ** Lemmas and Tactics About Decidable Propositions
        XXX: The lemma [dec_iff] should have been included in
        [Decidable.v].  Some form of the [solve_decidable]
        tactics below would also make sense in [Decidable.v].
        *)

    Lemma dec_iff : forall P Q : Prop,
      decidable P ->
      decidable Q ->
      decidable (P <-> Q).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    (** With this hint database, we can leverage [auto] to check
        decidability of propositions. *)
    Hint Resolve
      dec_True dec_False dec_or dec_and dec_imp dec_not dec_iff
    : decidable_prop.

    (** [solve_decidable using lib] will solve goals about the
        decidability of a proposition, assisted by an auxiliary
        database of lemmas.  The database is intended to contain
        lemmas stating the decidability of base propositions,
        (e.g., the decidability of equality on a particular
        inductive type). *)
    Tactic Notation "solve_decidable" "using" ident(db) :=
      match goal with
      | |- decidable ?P =>
        solve [ auto 100 with decidable_prop db ]
      end.

    Tactic Notation "solve_decidable" :=
      solve_decidable using core.

    (** ** Propositional Equivalences Involving Negation
        These are all written with the unfolded form of
        negation, since I am not sure if setoid rewriting will
        always perform conversion. *)

    (** *** Eliminating Negations
        We begin with lemmas that, when read from left to right,
        can be understood as ways to eliminate uses of [not]. *)

    Lemma not_true_iff :
      (True -> False) <-> False.
    Proof.
      tauto.
    Qed.

    Lemma not_false_iff :
      (False -> False) <-> True.
    Proof.
      tauto.
    Qed.

    Lemma not_not_iff : forall P : Prop,
      decidable P ->
      (((P -> False) -> False) <-> P).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma contrapositive : forall P Q : Prop,
      decidable P ->
      (((P -> False) -> (Q -> False)) <-> (Q -> P)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma or_not_l_iff_1 : forall P Q : Prop,
      decidable P ->
      ((P -> False) \/ Q <-> (P -> Q)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma or_not_l_iff_2 : forall P Q : Prop,
      decidable Q ->
      ((P -> False) \/ Q <-> (P -> Q)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma or_not_r_iff_1 : forall P Q : Prop,
      decidable P ->
      (P \/ (Q -> False) <-> (Q -> P)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma or_not_r_iff_2 : forall P Q : Prop,
      decidable Q ->
      (P \/ (Q -> False) <-> (Q -> P)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma imp_not_l : forall P Q : Prop,
      decidable P ->
      (((P -> False) -> Q) <-> (P \/ Q)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    (** *** Moving Negations Around
        We have four lemmas that, when read from left to right,
        describe how to push negations toward the leaves of a
        proposition and, when read from right to left, describe
        how to pull negations toward the top of a proposition. *)

    Lemma not_or_iff : forall P Q : Prop,
      (P \/ Q -> False) <-> (P -> False) /\ (Q -> False).
    Proof.
      tauto.
    Qed.

    Lemma not_and_iff : forall P Q : Prop,
      (P /\ Q -> False) <-> (P -> Q -> False).
    Proof.
      tauto.
    Qed.

    Lemma not_imp_iff : forall P Q : Prop,
      decidable P ->
      (((P -> Q) -> False) <-> P /\ (Q -> False)).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    Lemma not_imp_rev_iff : forall P Q : Prop,
      decidable P ->
      (((P -> Q) -> False) <-> (Q -> False) /\ P).
    Proof.
      unfold decidable in *. tauto.
    Qed.

    (** ** Tactics for Negations *)

    Tactic Notation "fold" "any" "not" :=
      repeat (
        match goal with
        | H: context [?P -> False] |- _ =>
          fold (~ P) in H
        | |- context [?P -> False] =>
          fold (~ P)
        end).

    (** [push not using db] will pushes all negations to the
        leaves of propositions in the goal, using the lemmas in
        [db] to assist in checking the decidability of the
        propositions involved.  If [using db] is omitted, then
        [core] will be used.  Additional versions are provided
        to manipulate the hypotheses or the hypotheses and goal
        together.

        XXX: This tactic and the similar subsequent ones should
        have been defined using [autorewrite].  However, there
        is a bug in the order that Coq generates subgoals when
        rewriting using a setoid.  In order to work around this
        bug, these tactics had to be written out in an explicit
        way.  When the bug is fixed these tactics will break!!
        *)

    Tactic Notation "push" "not" "using" ident(db) :=
      unfold not, iff;
      repeat (
        match goal with
        (** simplification by not_true_iff *)
        | |- context [True -> False] =>
          rewrite not_true_iff
        (** simplification by not_false_iff *)
        | |- context [False -> False] =>
          rewrite not_false_iff
        (** simplification by not_not_iff *)
        | |- context [(?P -> False) -> False] =>
          rewrite (not_not_iff P);
            [ solve_decidable using db | ]
        (** simplification by contrapositive *)
        | |- context [(?P -> False) -> (?Q -> False)] =>
          rewrite (contrapositive P Q);
            [ solve_decidable using db | ]
        (** simplification by or_not_l_iff_1/_2 *)
        | |- context [(?P -> False) \/ ?Q] =>
          (rewrite (or_not_l_iff_1 P Q);
            [ solve_decidable using db | ]) ||
          (rewrite (or_not_l_iff_2 P Q);
            [ solve_decidable using db | ])
        (** simplification by or_not_r_iff_1/_2 *)
        | |- context [?P \/ (?Q -> False)] =>
          (rewrite (or_not_r_iff_1 P Q);
            [ solve_decidable using db | ]) ||
          (rewrite (or_not_r_iff_2 P Q);
            [ solve_decidable using db | ])
        (** simplification by imp_not_l *)
        | |- context [(?P -> False) -> ?Q] =>
          rewrite (imp_not_l P Q);
            [ solve_decidable using db | ]
        (** rewriting by not_or_iff *)
        | |- context [?P \/ ?Q -> False] =>
          rewrite (not_or_iff P Q)
        (** rewriting by not_and_iff *)
        | |- context [?P /\ ?Q -> False] =>
          rewrite (not_and_iff P Q)
        (** rewriting by not_imp_iff *)
        | |- context [(?P -> ?Q) -> False] =>
          rewrite (not_imp_iff P Q);
            [ solve_decidable using db | ]
        end);
      fold any not.

    Tactic Notation "push" "not" :=
      push not using core.

    Tactic Notation
      "push" "not" "in" "*" "|-" "using" ident(db) :=
      unfold not, iff in * |-;
      repeat (
        match goal with
        (** simplification by not_true_iff *)
        | H: context [True -> False] |- _ =>
          rewrite not_true_iff in H
        (** simplification by not_false_iff *)
        | H: context [False -> False] |- _ =>
          rewrite not_false_iff in H
        (** simplification by not_not_iff *)
        | H: context [(?P -> False) -> False] |- _ =>
          rewrite (not_not_iff P) in H;
            [ | solve_decidable using db ]
        (** simplification by contrapositive *)
        | H: context [(?P -> False) -> (?Q -> False)] |- _ =>
          rewrite (contrapositive P Q) in H;
            [ | solve_decidable using db ]
        (** simplification by or_not_l_iff_1/_2 *)
        | H: context [(?P -> False) \/ ?Q] |- _ =>
          (rewrite (or_not_l_iff_1 P Q) in H;
            [ | solve_decidable using db ]) ||
          (rewrite (or_not_l_iff_2 P Q) in H;
            [ | solve_decidable using db ])
        (** simplification by or_not_r_iff_1/_2 *)
        | H: context [?P \/ (?Q -> False)] |- _ =>
          (rewrite (or_not_r_iff_1 P Q) in H;
            [ | solve_decidable using db ]) ||
          (rewrite (or_not_r_iff_2 P Q) in H;
            [ | solve_decidable using db ])
        (** simplification by imp_not_l *)
        | H: context [(?P -> False) -> ?Q] |- _ =>
          rewrite (imp_not_l P Q) in H;
            [ | solve_decidable using db ]
        (** rewriting by not_or_iff *)
        | H: context [?P \/ ?Q -> False] |- _ =>
          rewrite (not_or_iff P Q) in H
        (** rewriting by not_and_iff *)
        | H: context [?P /\ ?Q -> False] |- _ =>
          rewrite (not_and_iff P Q) in H
        (** rewriting by not_imp_iff *)
        | H: context [(?P -> ?Q) -> False] |- _ =>
          rewrite (not_imp_iff P Q) in H;
            [ | solve_decidable using db ]
        end);
      fold any not.

    Tactic Notation "push" "not" "in" "*" "|-"  :=
      push not in * |- using core.

    Tactic Notation "push" "not" "in" "*" "using" ident(db) :=
      push not using db; push not in * |- using db.
    Tactic Notation "push" "not" "in" "*" :=
      push not in * using core.

    (** A simple test case to see how this works.  *)
    Lemma test_push : forall P Q R : Prop,
      decidable P ->
      decidable Q ->
      (~ True) ->
      (~ False) ->
      (~ ~ P) ->
      (~ (P /\ Q) -> ~ R) ->
      ((P /\ Q) \/ ~ R) ->
      (~ (P /\ Q) \/ R) ->
      (R \/ ~ (P /\ Q)) ->
      (~ R \/ (P /\ Q)) ->
      (~ P -> R) ->
      (~ ((R -> P) \/ (R -> Q))) ->
      (~ (P /\ R)) ->
      (~ (P -> R)) ->
      True.
    Proof.
      intros. push not in *. tauto.
    Qed.

    (** [pull not using db] will pull as many negations as
        possible toward the top of the propositions in the goal,
        using the lemmas in [db] to assist in checking the
        decidability of the propositions involved.  If [using
        db] is omitted, then [core] will be used.  Additional
        versions are provided to manipulate the hypotheses or
        the hypotheses and goal together. *)

    Tactic Notation "pull" "not" "using" ident(db) :=
      unfold not, iff;
      repeat (
        match goal with
        (** simplification by not_true_iff *)
        | |- context [True -> False] =>
          rewrite not_true_iff
        (** simplification by not_false_iff *)
        | |- context [False -> False] =>
          rewrite not_false_iff
        (** simplification by not_not_iff *)
        | |- context [(?P -> False) -> False] =>
          rewrite (not_not_iff P);
            [ solve_decidable using db | ]
        (** simplification by contrapositive *)
        | |- context [(?P -> False) -> (?Q -> False)] =>
          rewrite (contrapositive P Q);
            [ solve_decidable using db | ]
        (** simplification by or_not_l_iff_1/_2 *)
        | |- context [(?P -> False) \/ ?Q] =>
          (rewrite (or_not_l_iff_1 P Q);
            [ solve_decidable using db | ]) ||
          (rewrite (or_not_l_iff_2 P Q);
            [ solve_decidable using db | ])
        (** simplification by or_not_r_iff_1/_2 *)
        | |- context [?P \/ (?Q -> False)] =>
          (rewrite (or_not_r_iff_1 P Q);
            [ solve_decidable using db | ]) ||
          (rewrite (or_not_r_iff_2 P Q);
            [ solve_decidable using db | ])
        (** simplification by imp_not_l *)
        | |- context [(?P -> False) -> ?Q] =>
          rewrite (imp_not_l P Q);
            [ solve_decidable using db | ]
        (** rewriting by not_or_iff *)
        | |- context [(?P -> False) /\ (?Q -> False)] =>
          rewrite <- (not_or_iff P Q)
        (** rewriting by not_and_iff *)
        | |- context [?P -> ?Q -> False] =>
          rewrite <- (not_and_iff P Q)
        (** rewriting by not_imp_iff *)
        | |- context [?P /\ (?Q -> False)] =>
          rewrite <- (not_imp_iff P Q);
            [ solve_decidable using db | ]
        (** rewriting by not_imp_rev_iff *)
        | |- context [(?Q -> False) /\ ?P] =>
          rewrite <- (not_imp_rev_iff P Q);
            [ solve_decidable using db | ]
        end);
      fold any not.

    Tactic Notation "pull" "not" :=
      pull not using core.

    Tactic Notation
      "pull" "not" "in" "*" "|-" "using" ident(db) :=
      unfold not, iff in * |-;
      repeat (
        match goal with
        (** simplification by not_true_iff *)
        | H: context [True -> False] |- _ =>
          rewrite not_true_iff in H
        (** simplification by not_false_iff *)
        | H: context [False -> False] |- _ =>
          rewrite not_false_iff in H
        (** simplification by not_not_iff *)
        | H: context [(?P -> False) -> False] |- _ =>
          rewrite (not_not_iff P) in H;
            [ | solve_decidable using db ]
        (** simplification by contrapositive *)
        | H: context [(?P -> False) -> (?Q -> False)] |- _ =>
          rewrite (contrapositive P Q) in H;
            [ | solve_decidable using db ]
        (** simplification by or_not_l_iff_1/_2 *)
        | H: context [(?P -> False) \/ ?Q] |- _ =>
          (rewrite (or_not_l_iff_1 P Q) in H;
            [ | solve_decidable using db ]) ||
          (rewrite (or_not_l_iff_2 P Q) in H;
            [ | solve_decidable using db ])
        (** simplification by or_not_r_iff_1/_2 *)
        | H: context [?P \/ (?Q -> False)] |- _ =>
          (rewrite (or_not_r_iff_1 P Q) in H;
            [ | solve_decidable using db ]) ||
          (rewrite (or_not_r_iff_2 P Q) in H;
            [ | solve_decidable using db ])
        (** simplification by imp_not_l *)
        | H: context [(?P -> False) -> ?Q] |- _ =>
          rewrite (imp_not_l P Q) in H;
            [ | solve_decidable using db ]
        (** rewriting by not_or_iff *)
        | H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
          rewrite <- (not_or_iff P Q) in H
        (** rewriting by not_and_iff *)
        | H: context [?P -> ?Q -> False] |- _ =>
          rewrite <- (not_and_iff P Q) in H
        (** rewriting by not_imp_iff *)
        | H: context [?P /\ (?Q -> False)] |- _ =>
          rewrite <- (not_imp_iff P Q) in H;
            [ | solve_decidable using db ]
        (** rewriting by not_imp_rev_iff *)
        | H: context [(?Q -> False) /\ ?P] |- _ =>
          rewrite <- (not_imp_rev_iff P Q) in H;
            [ | solve_decidable using db ]
        end);
      fold any not.

    Tactic Notation "pull" "not" "in" "*" "|-"  :=
      pull not in * |- using core.

    Tactic Notation "pull" "not" "in" "*" "using" ident(db) :=
      pull not using db; pull not in * |- using db.
    Tactic Notation "pull" "not" "in" "*" :=
      pull not in * using core.

    (** A simple test case to see how this works.  *)
    Lemma test_pull : forall P Q R : Prop,
      decidable P ->
      decidable Q ->
      (~ True) ->
      (~ False) ->
      (~ ~ P) ->
      (~ (P /\ Q) -> ~ R) ->
      ((P /\ Q) \/ ~ R) ->
      (~ (P /\ Q) \/ R) ->
      (R \/ ~ (P /\ Q)) ->
      (~ R \/ (P /\ Q)) ->
      (~ P -> R) ->
      (~ (R -> P) /\ ~ (R -> Q)) ->
      (~ P \/ ~ R) ->
      (P /\ ~ R) ->
      (~ R /\ P) ->
      True.
    Proof.
      intros. pull not in *. tauto.
    Qed.

  End FSetLogicalFacts.
  Import FSetLogicalFacts.

  (** * Auxiliary Tactics
      Again, these lemmas and tactics are in a module so that
      they do not affect the namespace if you import the
      enclosing module [Decide].  *)
  Module FSetDecideAuxiliary.

    (** ** Generic Tactics
        We begin by defining a few generic, useful tactics. *)

    (** [if t then t1 else t2] executes [t] and, if it does not
        fail, then [t1] will be applied to all subgoals
        produced.  If [t] fails, then [t2] is executed. *)
    Tactic Notation
      "if" tactic(t)
      "then" tactic(t1)
      "else" tactic(t2) :=
      first [ t; first [ t1 | fail 2 ] | t2 ].

    (** [prop P holds by t] succeeds (but does not modify the
        goal or context) if the proposition [P] can be proved by
        [t] in the current context.  Otherwise, the tactic
        fails. *)
    Tactic Notation "prop" constr(P) "holds" "by" tactic(t) :=
      let H := fresh in
      assert P as H by t;
      clear H.

    (** This tactic acts just like [assert ... by ...] but will
        fail if the context already contains the proposition. *)
    Tactic Notation "assert" "new" constr(e) "by" tactic(t) :=
      match goal with
      | H: e |- _ => fail 1
      | _ => assert e by t
      end.

    (** [subst++] is similar to [subst] except that
        - it never fails (as [subst] does on recursive
          equations),
        - it substitutes locally defined variable for their
          definitions,
        - it performs beta reductions everywhere, which may
          arise after substituting a locally defined function
          for its definition.
        *)
    Tactic Notation "subst" "++" :=
      repeat (
        match goal with
        | x : _ |- _ => subst x
        end);
      cbv zeta beta in *.

    (** If you have a negated goal and [H] is a negated
        hypothesis, then [contra H] exchanges your goal and [H],
        removing the negations.  (Just like [swap] but reuses
        the same name. *)
    Ltac contra H :=
      let J := fresh in
      unfold not;
      unfold not in H;
      intros J;
      apply H;
      clear H;
      rename J into H.

    (** [decompose records] calls [decompose record H] on every
        relevant hypothesis [H]. *)
    Tactic Notation "decompose" "records" :=
      repeat (
        match goal with
        | H: _ |- _ => progress (decompose record H); clear H
        end).

    (** ** Discarding Irrelevant Hypotheses
        We will want to clear the context of any
        non-FSet-related hypotheses in order to increase the
        speed of the tactic.  To do this, we will need to be
        able to decide which are relevant.  We do this by making
        a simple inductive definition classifying the
        propositions of interest. *)

    Inductive FSet_elt_Prop : Prop -> Prop :=
    | eq_Prop : forall (S : Set) (x y : S),
        FSet_elt_Prop (x = y)
    | eq_elt_prop : forall x y,
        FSet_elt_Prop (E.eq x y)
    | In_elt_prop : forall x s,
        FSet_elt_Prop (In x s)
    | True_elt_prop :
        FSet_elt_Prop True
    | False_elt_prop :
        FSet_elt_Prop False
    | conj_elt_prop : forall P Q,
        FSet_elt_Prop P ->
        FSet_elt_Prop Q ->
        FSet_elt_Prop (P /\ Q)
    | disj_elt_prop : forall P Q,
        FSet_elt_Prop P ->
        FSet_elt_Prop Q ->
        FSet_elt_Prop (P \/ Q)
    | impl_elt_prop : forall P Q,
        FSet_elt_Prop P ->
        FSet_elt_Prop Q ->
        FSet_elt_Prop (P -> Q)
    | not_elt_prop : forall P,
        FSet_elt_Prop P ->
        FSet_elt_Prop (~ P).

    Inductive FSet_Prop : Prop -> Prop :=
    | elt_FSet_Prop : forall P,
        FSet_elt_Prop P ->
        FSet_Prop P
    | Empty_FSet_Prop : forall s,
        FSet_Prop (Empty s)
    | Subset_FSet_Prop : forall s1 s2,
        FSet_Prop (Subset s1 s2)
    | Equal_FSet_Prop : forall s1 s2,
        FSet_Prop (Equal s1 s2).

    (** Here is the tactic that will throw away hypotheses that
        are not useful (for the intended scope of the [fsetdec]
        tactic). *)
    Hint Constructors FSet_elt_Prop FSet_Prop : FSet_Prop.
    Ltac discard_nonFSet :=
      decompose records;
      repeat (
        match goal with
        | H : ?P |- _ =>
          if prop (FSet_Prop P) holds by
            (auto 100 with FSet_Prop)
          then fail
          else clear H
        end).

    (** ** Turning Set Operators into Propositional Connectives
        The lemmas from [FSetFacts] will be used to break down
        set operations into propositional formulas built over
        the predicates [In] and [E.eq] applied only to
        variables.  We are going to use them with [autorewrite].
        *)
    Module F := FSetFacts.Facts M.
    Hint Rewrite
      F.empty_iff F.singleton_iff F.add_iff F.remove_iff
      F.union_iff F.inter_iff F.diff_iff
    : set_simpl.

    (** ** Decidability of FSet Propositions *)

    (** [In] is decidable. *)
    Module D := DepOfNodep M.
    Lemma dec_In : forall x s,
      decidable (In x s).
    Proof.
      intros x s. red. destruct (D.mem x s); auto.
    Qed.

    (** [E.eq] is decidable. *)
    Lemma dec_eq : forall (x y : E.t),
      decidable (E.eq x y).
    Proof.
      intros x y. red. destruct (E.compare x y); auto.
    Qed.

    (** The hint database [FSet_decidability] will be given to
        the [push_neg] tactic from the module [Negation]. *)
    Hint Resolve dec_In dec_eq : FSet_decidability.

    (** ** Normalizing Propositions About Equality
        We have to deal with the fact that [E.eq] may be
        convertible with Coq's equality.  Thus, we will find the
        following tactics useful to replace one form with the
        other everywhere. *)

    (** The next tactic, [Logic_eq_to_E_eq], mentions the term
        [E.t]; thus, we must ensure that [E.t] is used in favor
        of any other convertible but syntactically distinct
        term. *)
    Ltac change_to_E_t :=
      repeat (
        match goal with
        | H : ?T |- _ =>
          progress (change T with E.t in H);
          repeat (
            match goal with
            | J : _ |- _ => progress (change T with E.t in J)
            | |- _ => progress (change T with E.t)
            end )
        end).

    (** These two tactics take us from Coq's built-in equality
        to [E.eq] (and vice versa) when possible. *)

    Ltac Logic_eq_to_E_eq :=
      repeat (
        match goal with
        | H: _ |- _ =>
          progress (change (@Logic.eq E.t) with E.eq in H)
        | |- _ =>
          progress (change (@Logic.eq E.t) with E.eq)
        end).

    Ltac E_eq_to_Logic_eq :=
      repeat (
        match goal with
        | H: _ |- _ =>
          progress (change E.eq with (@Logic.eq E.t) in H)
        | |- _ =>
          progress (change E.eq with (@Logic.eq E.t))
        end).

    (** This tactic works like the built-in tactic [subst], but
        at the level of set element equality (which may not be
        the convertible with Coq's equality). *)
    Ltac substFSet :=
      repeat (
        match goal with
        | H: E.eq ?x ?y |- _ => rewrite H in *; clear H
        end).

    (** ** Considering Decidability of Base Propositions
        This tactic adds assertions about the decidability of
        [E.eq] and [In] to the context.  This is necessary for
        the completeness of the [fsetdec] tactic.  However, in
        order to minimize the cost of proof search, we should be
        careful to not add more than we need.  Once negations
        have been pushed to the leaves of the propositions, we
        only need to worry about decidability for those base
        propositions that appear in a negated form. *)
    Ltac assert_decidability :=
      (** We actually don't want these rules to fire if the
          syntactic context in the patterns below is trivially
          empty, but we'll just do some clean-up at the
          afterward.  *)
      repeat (
        match goal with
        | H: context [~ E.eq ?x ?y] |- _ =>
          assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
        | H: context [~ In ?x ?s] |- _ =>
          assert new (In x s \/ ~ In x s) by (apply dec_In)
        | |- context [~ E.eq ?x ?y] =>
          assert new (E.eq x y \/ ~ E.eq x y) by (apply dec_eq)
        | |- context [~ In ?x ?s] =>
          assert new (In x s \/ ~ In x s) by (apply dec_In)
        end);
      (** Now we eliminate the useless facts we added (because
          they would likely be very harmful to performance). *)
      repeat (
        match goal with
        | _: ~ ?P, H : ?P \/ ~ ?P |- _ => clear H
        end).

    (** ** Handling [Empty], [Subset], and [Equal]
        This tactic instantiates universally quantified
        hypotheses (which arise from the unfolding of [Empty],
        [Subset], and [Equal]) for each of the set element
        expressions that is involved in some membership or
        equality fact.  Then it throws away those hypotheses,
        which should no longer be needed. *)
    Ltac inst_FSet_hypotheses :=
      repeat (
        match goal with
        | H : forall a : E.t, _,
          _ : context [ In ?x _ ] |- _ =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        | H : forall a : E.t, _
          |- context [ In ?x _ ] =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        | H : forall a : E.t, _,
          _ : context [ E.eq ?x _ ] |- _ =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        | H : forall a : E.t, _
          |- context [ E.eq ?x _ ] =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        | H : forall a : E.t, _,
          _ : context [ E.eq _ ?x ] |- _ =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        | H : forall a : E.t, _
          |- context [ E.eq _ ?x ] =>
          let P := type of (H x) in
          assert new P by (exact (H x))
        end);
      repeat (
        match goal with
        | H : forall a : E.t, _ |- _ =>
          clear H
        end).

    (** ** The Core [fsetdec] Auxiliary Tactics *)

    (** Here is the crux of the proof search.  Recursion through
        [intuition]!  (This will terminate if I correctly
        understand the behavior of [intuition].) *)
    Ltac fsetdec_rec :=
      try (match goal with
      | H: E.eq ?x ?x -> False |- _ => destruct H
      end);
      (reflexivity ||
      contradiction ||
      (progress substFSet; intuition fsetdec_rec)).

    (** If we add [unfold Empty, Subset, Equal in *; intros;] to
        the beginning of this tactic, it will satisfy the same
        specification as the [fsetdec] tactic; however, it will
        be much slower than necessary without the pre-processing
        done by the wrapper tactic [fsetdec]. *)
    Ltac fsetdec_body :=
      inst_FSet_hypotheses;
      autorewrite with set_simpl in *;
      push not in * using FSet_decidability;
      substFSet;
      assert_decidability;
      auto using E.eq_refl;
      (intuition fsetdec_rec) ||
      fail 1
        "because the goal is beyond the scope of this tactic".

  End FSetDecideAuxiliary.
  Import FSetDecideAuxiliary.

  (** * The [fsetdec] Tactic
      Here is the top-level tactic (the only one intended for
      clients of this library).  It's specification is given at
      the top of the file. *)
  Ltac fsetdec :=
    (** We first unfold any occurrences of [iff]. *)
    unfold iff in *;
    (** We fold occurrences of [not] because it is better for
        [intros] to leave us with a goal of [~ P] than a goal of
        [False]. *)
    fold any not; intros;
    (** Now we decompose conjunctions, which will allow the
        [discard_nonFSet] and [assert_decidability] tactics to
        do a much better job. *)
    decompose records;
    discard_nonFSet;
    (** We unfold these defined propositions on finite sets.  If
        our goal was one of them, then have one more item to
        introduce now. *)
    unfold Empty, Subset, Equal in *; intros;
    (** We now want to get rid of all uses of [=] in favor of
        [E.eq].  However, the best way to eliminate a [=] in
        the context is with [subst], so we will try that first.
        In fact, we may as well convert uses of [E.eq] into [=]
        where possible before we do [subst] so that we can get
        even more mileage out of it.  Then we will convert all
        remaining uses of [=] back to [E.eq] when possible.  We
        use [change_to_E_t] to ensure that we have a canonical
        name for set elements, so that [Logic_eq_to_E_eq] will
        work properly. *)
    change_to_E_t; E_eq_to_Logic_eq; subst++; Logic_eq_to_E_eq;
    (** The next optimization is to swap a negated goal with a
        negated hypothesis when possible.  Any swap will improve
        performance by eliminating the total number of
        negations, but we will get the maximum benefit if we
        swap the goal with a hypotheses mentioning the same set
        element, so we try that first.  If we reach the fourth
        branch below, we attempt any swap.  However, to maintain
        completeness of this tactic, we can only perform such a
        swap with a decidable proposition; hence, we first test
        whether the hypothesis is an [FSet_elt_Prop], noting
        that any [FSet_elt_Prop] is decidable. *)
    pull not using FSet_decidability;
    unfold not in *;
    match goal with
    | H: (In ?x ?r) -> False |- (In ?x ?s) -> False =>
      contra H; fsetdec_body
    | H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
      contra H; fsetdec_body
    | H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
      contra H; fsetdec_body
    | H: ?P -> False |- ?Q -> False =>
      if prop (FSet_elt_Prop P) holds by
        (auto 100 with FSet_Prop)
      then (contra H; fsetdec_body)
      else fsetdec_body
    | |- _ =>
      fsetdec_body
    end.

  (** * Examples *)

  Module FSetDecideTestCases.

    Lemma test_eq_trans_1 : forall x y z s,
      E.eq x y ->
      ~ ~ E.eq z y ->
      In x s ->
      In z s.
    Proof. fsetdec. Qed.

    Lemma test_eq_trans_2 : forall x y z r s,
      In x (singleton y) ->
      ~ In z r ->
      ~ ~ In z (add y r) ->
      In x s ->
      In z s.
    Proof. fsetdec. Qed.

    Lemma test_eq_neq_trans_1 : forall w x y z s,
      E.eq x w ->
      ~ ~ E.eq x y ->
      ~ E.eq y z ->
      In w s ->
      In w (remove z s).
    Proof. fsetdec. Qed.

    Lemma test_eq_neq_trans_2 : forall w x y z r1 r2 s,
      In x (singleton w) ->
      ~ In x r1 ->
      In x (add y r1) ->
      In y r2 ->
      In y (remove z r2) ->
      In w s ->
      In w (remove z s).
    Proof. fsetdec. Qed.

    Lemma test_In_singleton : forall x,
      In x (singleton x).
    Proof. fsetdec. Qed.

    Lemma test_Subset_add_remove : forall x s,
      s [<=] (add x (remove x s)).
    Proof. fsetdec. Qed.

    Lemma test_eq_disjunction : forall w x y z,
      In w (add x (add y (singleton z))) ->
      E.eq w x \/ E.eq w y \/ E.eq w z.
    Proof. fsetdec. Qed.

    Lemma test_not_In_disj : forall x y s1 s2 s3 s4,
      ~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
      ~ (In x s1 \/ In x s4 \/ E.eq y x).
    Proof. fsetdec. Qed.

    Lemma test_not_In_conj : forall x y s1 s2 s3 s4,
      ~ In x (union s1 (union s2 (union s3 (add y s4)))) ->
      ~ In x s1 /\ ~ In x s4 /\ ~ E.eq y x.
    Proof. fsetdec. Qed.

    Lemma test_iff_conj : forall a x s s',
    (In a s' <-> E.eq x a \/ In a s) ->
    (In a s' <-> In a (add x s)).
    Proof. fsetdec. Qed.

    Lemma test_set_ops_1 : forall x q r s,
      (singleton x) [<=] s ->
      Empty (union q r) ->
      Empty (inter (diff s q) (diff s r)) ->
      ~ In x s.
    Proof. fsetdec. Qed.

    Lemma eq_chain_test : forall x1 x2 x3 x4 s1 s2 s3 s4,
      Empty s1 ->
      In x2 (add x1 s1) ->
      In x3 s2 ->
      ~ In x3 (remove x2 s2) ->
      ~ In x4 s3 ->
      In x4 (add x3 s3) ->
      In x1 s4 ->
      Subset (add x4 s4) s4.
    Proof. fsetdec. Qed.

    Lemma test_too_complex : forall x y z r s,
      E.eq x y ->
      (In x (singleton y) -> r [<=] s) ->
      In z r ->
      In z s.
    Proof.
      (** [fsetdec] is not intended to solve this directly. *)
      intros until s; intros Heq H Hr; lapply H; fsetdec.
    Qed.

    Lemma function_test_1 :
      forall (f : t -> t),
      forall (g : elt -> elt),
      forall (s1 s2 : t),
      forall (x1 x2 : elt),
      Equal s1 (f s2) ->
      E.eq x1 (g (g x2)) ->
      In x1 s1 ->
      In (g (g x2)) (f s2).
    Proof. fsetdec. Qed.

    Lemma function_test_2 :
      forall (f : t -> t),
      forall (g : elt -> elt),
      forall (s1 s2 : t),
      forall (x1 x2 : elt),
      Equal s1 (f s2) ->
      E.eq x1 (g x2) ->
      In x1 s1 ->
      g x2 = g (g x2) ->
      In (g (g x2)) (f s2).
    Proof.
      (** [fsetdec] is not intended to solve this directly. *)
      intros until 3. intros g_eq. rewrite <- g_eq. fsetdec.
    Qed.

  End FSetDecideTestCases.

End Decide.


Require Export GeoCoq.Elements.OriginalProofs.lemma_NChelper.
Require Export GeoCoq.Elements.OriginalProofs.proposition_20.
Require Export GeoCoq.Elements.OriginalProofs.lemma_21helper.
Require Export GeoCoq.Elements.OriginalProofs.lemma_TTorder.
Require Export GeoCoq.Elements.OriginalProofs.lemma_TTflip.
Require Export GeoCoq.Elements.OriginalProofs.lemma_TTtransitive.
Require Export GeoCoq.Elements.OriginalProofs.lemma_TTflip2.
Require Export GeoCoq.Elements.OriginalProofs.lemma_NCdistinct.

Section Euclid.

Context `{Ax:euclidean_neutral_ruler_compass}.

Lemma proposition_21 :
   forall A B C D E,
   Triangle A B C -> BetS A E C -> BetS B D E ->
   TT B A A C B D D C /\ LtA B A C B D C.
Proof.
intros.
assert (BetS E D B) by (conclude axiom_betweennesssymmetry).
assert (nCol A B C) by (conclude_def Triangle ).
assert (Col A E C) by (conclude_def Col ).
assert (Col A C E) by (forward_using lemma_collinearorder).
assert (neq A E) by (forward_using lemma_betweennotequal).
assert (nCol A C B) by (forward_using lemma_NCorder).
assert (eq A A) by (conclude cn_equalityreflexive).
assert (Col A C A) by (conclude_def Col ).
assert (nCol A E B) by (conclude lemma_NChelper).
assert (nCol A B E) by (forward_using lemma_NCorder).
assert (Triangle A B E) by (conclude_def Triangle ).
assert (TG B A A E B E) by (conclude proposition_20).
assert (TT B A A C B E E C) by (conclude lemma_21helper).
assert (nCol A C B) by (forward_using lemma_NCorder).
assert (Col A E C) by (conclude_def Col ).
assert (Col A C E) by (forward_using lemma_collinearorder).
assert (eq C C) by (conclude cn_equalityreflexive).
assert (Col A C C) by (conclude_def Col ).
assert (neq E C) by (forward_using lemma_betweennotequal).
assert (nCol E C B) by (conclude lemma_NChelper).
assert (nCol E B C) by (forward_using lemma_NCorder).
assert (Col E D B) by (conclude_def Col ).
assert (Col E B D) by (forward_using lemma_collinearorder).
assert (eq E E) by (conclude cn_equalityreflexive).
assert (Col E B E) by (conclude_def Col ).
assert (neq E D) by (forward_using lemma_betweennotequal).
assert (nCol E D C) by (conclude lemma_NChelper).
assert (nCol E C D) by (forward_using lemma_NCorder).
assert (Triangle E C D) by (conclude_def Triangle ).
assert (TG C E E D C D) by (conclude proposition_20).
assert (TT C E E B C D D B) by (conclude lemma_21helper).
assert (TT E B C E C D D B) by (conclude lemma_TTorder).
assert (TT B E E C C D D B) by (conclude lemma_TTflip).
assert (TT B A A C C D D B) by (conclude lemma_TTtransitive).
assert (TT B A A C B D D C) by (conclude lemma_TTflip2).
assert (nCol C E D) by (forward_using lemma_NCorder).
assert (Triangle C E D) by (conclude_def Triangle ).
assert (LtA D E C C D B) by (conclude proposition_16).
assert (nCol E B C) by (forward_using lemma_NCorder).
assert (eq B B) by (conclude cn_equalityreflexive).
assert (Col E B B) by (conclude_def Col ).
assert (Col E D B) by (conclude_def Col ).
assert (Col E B D) by (forward_using lemma_collinearorder).
assert (neq B D) by (forward_using lemma_betweennotequal).
assert (neq D B) by (conclude lemma_inequalitysymmetric).
assert (nCol D B C) by (conclude lemma_NChelper).
assert (nCol B A E) by (forward_using lemma_NCorder).
assert (Triangle B A E) by (conclude_def Triangle ).
assert (LtA E A B B E C) by (conclude proposition_16).
assert (CongA B A E E A B) by (conclude lemma_ABCequalsCBA).
assert (LtA B A E B E C) by (conclude lemma_angleorderrespectscongruence2).
assert (nCol C E B) by (forward_using lemma_NCorder).
assert (CongA C E B B E C) by (conclude lemma_ABCequalsCBA).
assert (LtA B A E C E B) by (conclude lemma_angleorderrespectscongruence).
assert (neq A E) by (forward_using lemma_betweennotequal).
assert (Out A E C) by (conclude lemma_ray4).
assert (Out A C E) by (conclude lemma_ray5).
assert (neq A B) by (forward_using lemma_NCdistinct).
assert (Out A B B) by (conclude lemma_ray4).
assert (nCol B A C) by (forward_using lemma_NCorder).
assert (CongA B A C B A C) by (conclude lemma_equalanglesreflexive).
assert (CongA B A C B A E) by (conclude lemma_equalangleshelper).
assert (BetS E D B) by (conclude axiom_betweennesssymmetry).
assert (Out E D B) by (conclude lemma_ray4).
assert (eq C C) by (conclude cn_equalityreflexive).
assert (Out E C C) by (conclude lemma_ray4).
assert (nCol C E D) by (forward_using lemma_NCorder).
assert (CongA C E D C E D) by (conclude lemma_equalanglesreflexive).
assert (CongA C E D C E B) by (conclude lemma_equalangleshelper).
assert (LtA B A E C E D) by (conclude lemma_angleorderrespectscongruence).
assert (LtA B A C C E D) by (conclude lemma_angleorderrespectscongruence2).
assert (nCol D E C) by (forward_using lemma_NCorder).
assert (CongA D E C C E D) by (conclude lemma_ABCequalsCBA).
assert (LtA B A C D E C) by (conclude lemma_angleorderrespectscongruence).
assert (LtA B A C C D B) by (conclude lemma_angleordertransitive).
assert (nCol B D C) by (forward_using lemma_NCorder).
assert (CongA B D C C D B) by (conclude lemma_ABCequalsCBA).
assert (LtA B A C B D C) by (conclude lemma_angleorderrespectscongruence).
close.
Qed.

End Euclid.


Require Import Rsequence_def Rpser_def Rpow_facts.

Require Import Cmet Cnorm Ctacfield.
Require Import Cpow.
Require Import Cprop_base.
Require Import Csequence_def Csequence_facts.
Require Import Cpser_def.
Require Import Lia.

Local Open Scope R_scope.
Local Open Scope C_scope.

(** * Some lemmas manipulating the definitions *)

Lemma Cv_radius_weak_0 : forall An, Cv_radius_weak An 0.
Proof.
intro An ; exists (Cnorm (An O)) ; intros x [n Hn] ; rewrite Hn ;
 unfold_gt ; destruct n.
  rewrite Cpow_0 ; right ; apply Cnorm_eq_compat ; intuition.
  rewrite IRC_pow_compat, pow_i, Cmult_0_r, Cnorm_C0 ; [apply Cnorm_pos | intuition].
Qed.

Lemma finite_cv_radius_pos : forall An r, finite_cv_radius An r -> 0 <= r.
Proof.
intros An r [_ Hf].
 destruct(Rle_lt_dec 0 r).
  trivial.
destruct (Hf R0).
trivial.
apply Cv_radius_weak_0.
Qed.

Lemma Cv_radius_weak_Cnorm_compat_rev : forall (An : nat -> C) (r : R),
       Cv_radius_weak (fun n => Cnorm (An n)) r -> Cv_radius_weak An r.
Proof.
intros An r [M HM] ; exists M.
 intros x [n Hn] ; rewrite Hn.
 unfold_gt ; rewrite Cnorm_Cmult, <- Cnorm_invol, <- Cnorm_Cmult ;
 apply HM ; exists n ; reflexivity.
Qed.

Lemma Cv_radius_weak_Cnorm_compat_rev2 : forall (An : nat -> C) (r : R),
       Rpser_def.Cv_radius_weak (fun n => Cnorm (An n)) r -> Cv_radius_weak An r.
Proof.
intros An r [M HM] ; apply Cv_radius_weak_Cnorm_compat_rev ;
 exists M ; intros x [n Hn] ; rewrite Hn ; unfold_gt ;
 rewrite Cnorm_Cmult, IRC_pow_compat ; do 2 rewrite Cnorm_IRC_Rabs ;
 rewrite <- Rabs_mult  ; apply HM ; exists n ; reflexivity.
Qed.

Lemma Cv_radius_weak_Cnorm_compat : forall (An : nat -> C) (r : R),
       Cv_radius_weak An r -> Cv_radius_weak (fun n => Cnorm (An n)) r.
Proof.
intros An r Rho.
elim Rho ; intros m Hm ; exists m ; unfold_gt ; intros a Ha ;
 unfold EUn in Ha ; elim Ha ; intros u Hu ; rewrite Hu ; rewrite Cnorm_Cmult ;
 rewrite Cnorm_invol, <- Cnorm_Cmult ; apply Hm.
 exists u ; unfold_gt ; rewrite IRC_pow_compat ; reflexivity.
Qed.

Lemma Cv_radius_weak_Cnorm_compat2 : forall (An : nat -> C) (r : R),
       Cv_radius_weak An r -> Rpser_def.Cv_radius_weak (fun n => Cnorm (An n)) r.
Proof.
intros An r Rho.
elim Rho ; intros m Hm ; exists m ; unfold_gt ;
 unfold gt_abs_pser, Rpser_def.gt_pser, Rseq_abs, Rseq_mult ; intros a Ha ;
 unfold EUn in Ha ; elim Ha ; intros u Hu ; rewrite Hu ; rewrite Rabs_mult ;
 do 2 rewrite <- Cnorm_IRC_Rabs ; rewrite Cnorm_invol, <- Cnorm_Cmult ; apply Hm.
 exists u ; unfold_gt ; rewrite IRC_pow_compat ; reflexivity.
Qed.

Lemma Cv_radius_weak_le_compat : forall (An : nat -> C) (r r' : R),
       Rabs r' <= Rabs r -> Cv_radius_weak An r -> Cv_radius_weak An r'.
Proof.
intros An r r' r'_bd Rho.
 case (Req_or_neq r') ; intro r_eq.
  rewrite r_eq ; exists (Cnorm (An 0%nat)) ; intros x Hx ; destruct Hx as (u, Hu) ;
  rewrite Hu ; unfold_gt ; clear ; induction u.
  apply Req_le ; apply Cnorm_eq_compat ; rewrite Cpow_0. apply Cmult_1_r.
  rewrite C0_pow ; [| intuition] ; rewrite Cmult_0_r ;
  rewrite Cnorm_C0 ; apply Cnorm_pos.
  assert (r_pos : 0 < Rabs r).
   apply Rlt_le_trans with (Rabs r') ; [apply Rabs_pos_lt |] ; assumption.
  assert (r_neq : r <> 0%R).
   case (Req_or_neq r) ; intro s ; [| assumption] ;
  apply False_ind ; rewrite s in r_pos ; rewrite Rabs_R0 in r_pos ; lra.
  destruct Rho as (C, HC) ; exists C ; intros x Hx ; destruct Hx as (u,Hu) ; rewrite Hu ;
  unfold_gt.
  replace (IRC r' ^ u) with ((IRC r' ^ u * /IRC r ^ u) * (IRC r ^ u)).
  repeat (rewrite Cnorm_Cmult) ; rewrite Rmult_comm ; rewrite <- Cnorm_Cmult at 1 ;
  rewrite Rmult_assoc ; rewrite <- Cnorm_Cmult.
  apply Rle_trans with (1 * Cnorm (IRC r ^ u * An u))%R.
  apply Rmult_le_compat_r ; [apply Cnorm_pos |].
  rewrite Cpow_inv. rewrite <- Cpow_mul_distr_l.
  rewrite Cnorm_pow.
  replace 1%R with (1 ^ u)%R.
  apply pow_le_compat. apply Cnorm_pos.
  rewrite Cnorm_Cmult ; replace (IZR 1) with (Cnorm (IRC r) * / Cnorm (IRC r))%R.
  rewrite Cnorm_inv ; repeat rewrite Cnorm_IRC_Rabs.
  apply Rmult_le_compat_r.
  left ; apply Rinv_0_lt_compat ; apply Rabs_pos_lt ; assumption.
  assumption.
  apply IRC_neq_0_compat ; assumption.
  field ; rewrite Cnorm_IRC_Rabs ; apply Rgt_not_eq ; assumption.
  apply pow1.
  apply IRC_neq_0_compat ; assumption.
  rewrite Rmult_1_l ; apply HC.
  exists u ; unfold_gt ; rewrite Cmult_comm ; reflexivity.
  field.
  rewrite IRC_pow_compat ; apply IRC_neq_0_compat ;
  apply pow_nonzero ; assumption.
Qed.

Lemma finite_cv_radius_weakening : forall An r, finite_cv_radius An r ->
      forall x, Rabs x < r -> Cv_radius_weak An x.
Proof.
intros An r [H_sup _] x Hx.
 apply Cv_radius_weak_le_compat with (Rabs x).
  rewrite Rabs_Rabsolu ; right ; reflexivity.
  apply H_sup ; split ; [apply Rabs_pos | assumption].
Qed.

Lemma Cv_radius_weak_padding_pos_compat : forall (An : nat -> C) (r : R),
     Cv_radius_weak An r -> forall N, Cv_radius_weak (fun n => An (n + N)%nat) r.
Proof.
intros An r Rho N.
 destruct (Req_dec r 0) as [r_eq | r_neq].
  rewrite r_eq ; exists (Cnorm (An N)).
  intros u Hu ; destruct Hu as [n Hn] ; rewrite Hn ; unfold_gt ; destruct n.
  simpl ; rewrite Cmult_1_r ; right ; reflexivity.
  rewrite Cnorm_Cmult, Cnorm_pow, Cnorm_IRC_Rabs, RPow_abs, pow_i,
  Rabs_R0, Rmult_0_r ; [apply Cnorm_pos | intuition].
 destruct Rho as [M HM].
 exists (M * (/ Rabs r) ^ N)%R.
 intros u Hu ; destruct Hu as [n Hn] ; rewrite Hn.
 unfold_gt ; simpl.
 rewrite Cnorm_Cmult ; apply Rle_trans with (Cnorm (An (n + N)%nat) * Cnorm (r ^ n) *
 (Rabs r ^ N) * ((/Rabs r) ^ N))%R.
 right ; repeat rewrite Rmult_assoc ; repeat apply Rmult_eq_compat_l.
 rewrite <- Rpow_mult_distr, Rinv_r, pow1, Rmult_1_r ; [reflexivity |
 apply Rabs_no_R0 ; assumption].
 apply Rmult_le_compat_r.
 apply pow_le ; left ; apply Rinv_0_lt_compat ; apply Rabs_pos_lt ; assumption.
 rewrite <- Cnorm_IRC_Rabs, Rmult_assoc, <- Cnorm_pow, <- Cnorm_Cmult.
 apply HM.
 exists (n + N)%nat ; unfold_gt.
 repeat rewrite Cnorm_Cmult ; apply IRC_eq_compat.
 apply Rmult_eq_compat_l ; rewrite <- Cnorm_Cmult ; apply Cnorm_eq_compat.
 symmetry ; apply Cpow_add.
Qed.

Lemma Cv_radius_weak_padding_neg_compat : forall (An : nat -> C) (r : R) (N : nat),
     Cv_radius_weak (fun n => An (n + N)%nat) r -> Cv_radius_weak An r.
Proof.
intros An r N Rho.
 destruct Rho as [M HM].
 destruct (Cseq_partial_bound (fun n => (An n) * r ^ n) N) as [M' HM'].
 destruct (Req_dec r 0) as [r_eq | r_neq].
 exists (Cnorm (An 0%nat)) ; intros u Hu ; destruct Hu as [n Hn] ; rewrite Hn.
  unfold_gt ; destruct n.
   simpl ; rewrite Cmult_1_r ; right ; reflexivity.
   rewrite Cnorm_Cmult, Cnorm_pow, Cnorm_IRC_Rabs, r_eq, Rabs_R0, pow_i,
   Rmult_0_r ; [apply Cnorm_pos | intuition].
 exists (Rmax (M * Cnorm (r ^ N)) M') ; intros u Hu ; destruct Hu as [n Hn] ; rewrite Hn.
 destruct (le_lt_dec n N) as [n_lb | n_ub].
 apply Rle_trans with M' ; [apply HM' | apply RmaxLess2] ; assumption.
 apply Rle_trans with (M * Cnorm (r ^ N))%R ; [| apply RmaxLess1] ; unfold_gt.
 apply Rle_trans with (Cnorm (An n * r ^ n) * (/ Cnorm (r ^ N)) * Cnorm (r ^ N))%R.
 right ; field ; apply Cnorm_no_R0.
 apply Cpow_neq_compat ; apply IRC_neq_compat ; assumption.
  apply Rmult_le_compat_r ; [apply Cnorm_pos |].
  apply HM ; exists (n - N)%nat.
  unfold_gt.
  rewrite Cnorm_pow, Rinv_pow, <- Cnorm_inv, <- Cnorm_pow, <- Cnorm_Cmult,
  <- Cpow_inv.
  assert (Hrew : (n = n - N + N)%nat).
   intuition lia.
   repeat rewrite Cnorm_Cmult ; rewrite Hrew at 1 ; rewrite Rmult_assoc ;
   apply Rmult_eq_compat_l ; rewrite <- Cnorm_Cmult ; apply Cnorm_eq_compat.
   rewrite Hrew at 1 ; rewrite Cpow_add, Cmult_assoc, Cinv_r, Cmult_1_r ;
   [reflexivity | apply Cpow_neq_compat ; apply IRC_neq_compat ; assumption].
   apply IRC_neq_compat ; assumption.
   apply IRC_neq_compat ; assumption.
   apply Cnorm_no_R0 ; apply IRC_neq_compat ; assumption.
Qed.

Lemma Cv_radius_weak_plus : forall (An Bn : nat -> C) (r1 r2 : R),
       Cv_radius_weak An r1 -> Cv_radius_weak Bn r2 ->
       Cv_radius_weak (fun n => An n + Bn n) (Rmin (Rabs r1) (Rabs r2)).
Proof.
intros An Bn r1 r2 RhoA RhoB.
assert (r''_bd1 : Rabs (Rmin (Rabs r1) (Rabs r2)) <= Rabs r1).
 unfold Rmin ; case (Rle_dec (Rabs r1) (Rabs r2)) ; intro H ;
 rewrite Rabs_Rabsolu ; intuition.
assert (r''_bd2 : Rabs (Rmin (Rabs r1) (Rabs r2)) <= Rabs r2).
 unfold Rmin ; case (Rle_dec (Rabs r1) (Rabs r2)) ; intro H ;
 rewrite Rabs_Rabsolu ; intuition.
assert (Rho'A := Cv_radius_weak_le_compat An _ _ r''_bd1 RhoA).
assert (Rho'B := Cv_radius_weak_le_compat Bn _ _ r''_bd2 RhoB).
 destruct Rho'A as (C, HC) ;
 destruct Rho'B as (C', HC') ;
 exists (C + C')%R.
 intros x Hx ; destruct Hx as (u, Hu) ; rewrite Hu ; unfold_gt.
 rewrite Cmult_add_distr_r ; apply Rle_trans with (Cnorm (An u *  IRC (Rmin (Rabs r1)
         (Rabs r2)) ^ u) + Cnorm (Bn u * IRC (Rmin (Rabs r1) (Rabs r2)) ^ u))%R ;
 [apply Cnorm_triang |].
 apply Rle_trans with (Cnorm (An u * IRC (Rmin (Rabs r1) (Rabs r2)) ^ u) + C')%R ;
 [apply Rplus_le_compat_l ; apply HC' | apply Rplus_le_compat_r ; apply HC] ;
 exists u ; intuition.
Qed.

Lemma Cv_radius_weak_opp : forall (An : nat -> C) (r : R),
       Cv_radius_weak An r ->
       Cv_radius_weak (fun n => - An n) r.
Proof.
intros An r Rho.
 destruct Rho as (C, HC) ; exists C ; intros x Hx ; destruct Hx as (u,Hu) ; rewrite Hu ;
 unfold_gt ; rewrite Copp_mult_distr_l_reverse ; rewrite Cnorm_opp ;
 apply HC ; exists u ; intuition.
Qed.

Lemma Cv_radius_weak_minus : forall (An Bn : nat -> C) (r1 r2 : R),
       Cv_radius_weak An r1 -> Cv_radius_weak Bn r2 ->
       Cv_radius_weak (fun n => An n - Bn n) (Rmin (Rabs r1) (Rabs r2)).
Proof.
intros An Bn r1 r2 RhoA RhoB.
 assert (Rho'B := Cv_radius_weak_opp Bn _ RhoB).
 unfold Rminus ; apply Cv_radius_weak_plus ; assumption.
Qed.

Lemma Rmin_ge_0 : forall x y, 0 <= x -> 0 <= y -> 0 <= Rmin x y.
Proof.
intros x y x_pos y_pos.
 unfold Rmin ; case (Rle_dec x y) ; intro h ; intuition.
Qed.

Lemma Pser_add : forall (An Bn : nat -> C) (z : C) (N : nat),
       sum_f_C0 (gt_pser (fun n => An n + Bn n) z) N = sum_f_C0 (gt_pser An z) N + sum_f_C0 (gt_pser Bn z) N.
Proof.
intros An Bn x N ; induction N.
 simpl ; unfold gt_pser, Cseq_mult ; field.
 assert (Hrew : forall a b c d e, c = d + e -> a + b + c = a + d + (b + e)).
  intros ; subst ; field.
 simpl ; rewrite IHN ; apply Hrew.
 unfold gt_pser, Cseq_mult ; field.
Qed.

Lemma Pser_minus : forall (An Bn : nat -> C) (x : C) (N : nat),
       sum_f_C0 (gt_pser (fun n => An n - Bn n) x) N = sum_f_C0 (gt_pser An x) N - sum_f_C0 (gt_pser Bn x) N.
Proof.
intros An Bn x N ; induction N.
 simpl ; unfold gt_pser, Cseq_mult ; field.
 assert (Hrew : forall a b c d e, c = d - e -> a - b + c = a + d - (b + e)).
  intros ; subst ; field.
 simpl ; rewrite IHN ; apply Hrew.
 unfold gt_pser, Cseq_mult ; field.
Qed.

Lemma Pser_Cseqcv_link : forall (An : nat -> C) (x l : C),
       Cpser An x l ->
       Cseq_cv (fun N : nat => sum_f_C0 (gt_pser An x) N) l.
Proof.
intros An x l H ; apply H.
Qed.

Lemma Pser_unique : forall (An : nat -> C) (x l1 l2 : C),
  Cpser An x l1 -> Cpser An x l2 -> l1 = l2.
Proof.
intros An x l1 l2 Hl1 Hl2.
 assert (T1 := Pser_Cseqcv_link _ _ _ Hl1) ;
 assert (T2 := Pser_Cseqcv_link _ _ _ Hl2) ;
 eapply Cseq_cv_unique ; eassumption.
Qed.

Lemma Cpser_unique_extentionality : forall (An Bn : nat -> C) (x l1 l2 : C),
	(forall n, An n = Bn n) ->
        Cpser An x l1 -> Cpser Bn x l2 -> l1 = l2.
Proof.
intros An Bn x l1 l2 An_eq_Bn Hl1 Hl2.
 assert (T1 := Pser_Cseqcv_link _ _ _ Hl1) ;
 assert (T2 := Pser_Cseqcv_link _ _ _ Hl2).
 assert (T3 : forall (n : nat), sum_f_C0 (fun n => (gt_pser An x) n) n
                  = sum_f_C0 (fun n => (gt_pser Bn x) n) n).
  intro n ; apply (sum_f_C0_eq_seq) ; intros ; unfold gt_pser, Cseq_mult ;
  rewrite An_eq_Bn ; reflexivity.
 assert (T4 := Cseq_cv_eq_compat _ _ _ T3 T1).
 eapply Cseq_cv_unique ; eassumption.
Qed.


Load LFindLoad.
From lfind Require Import LFind.
Require Import Arith.
From adtind Require Import goal41.

Set Printing Depth 1000.
Definition lfind_eval  y z:=
append z y.

Compute lfind_eval  (Nil) (Cons Zero (Cons Zero Nil)).

Compute lfind_eval  (Cons Zero (Cons Zero Nil)) (Cons Zero Nil).

Compute lfind_eval  (Nil) (Cons Zero Nil).

Compute lfind_eval  (Cons (Succ (Succ Zero)) (Cons (Succ (Succ Zero)) (Cons Zero (Cons (Succ Zero) Nil)))) (Nil).

Compute lfind_eval  (Cons Zero Nil) (Nil).

Compute lfind_eval  (Nil) (Cons (Succ (Succ Zero)) (Cons (Succ (Succ Zero)) Nil)).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Nil) (Cons (Succ (Succ Zero)) (Cons (Succ Zero) Nil)).

Compute lfind_eval  (Cons Zero (Cons (Succ (Succ Zero)) Nil)) (Cons Zero Nil).

Compute lfind_eval  (Cons Zero Nil) (Nil).

Compute lfind_eval  (Cons Zero (Cons Zero Nil)) (Cons (Succ (Succ Zero)) (Cons (Succ (Succ Zero)) Nil)).

Compute lfind_eval  (Cons Zero (Cons (Succ (Succ Zero)) (Cons (Succ Zero) Nil))) (Nil).

Compute lfind_eval  (Cons (Succ Zero) (Cons Zero (Cons (Succ (Succ Zero)) (Cons (Succ Zero) (Cons Zero Nil))))) (Nil).

Compute lfind_eval  (Cons (Succ (Succ (Succ (Succ (Succ Zero))))) Nil) (Cons Zero Nil).

Compute lfind_eval  (Cons (Succ Zero) Nil) (Cons Zero Nil).

Compute lfind_eval  (Cons (Succ Zero) Nil) (Nil).

Compute lfind_eval  (Nil) (Cons (Succ (Succ Zero)) (Cons Zero (Cons Zero Nil))).

Compute lfind_eval  (Cons (Succ Zero) Nil) (Cons Zero Nil).

Compute lfind_eval  (Cons Zero Nil) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Nil) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Cons Zero Nil) (Cons (Succ Zero) (Cons (Succ Zero) Nil)).

Compute lfind_eval  (Cons Zero (Cons (Succ (Succ Zero)) Nil)) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Cons Zero (Cons (Succ Zero) Nil)) (Nil).

Compute lfind_eval  (Cons Zero Nil) (Cons Zero Nil).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Cons (Succ (Succ Zero)) (Cons (Succ Zero) Nil)) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Cons Zero (Cons (Succ (Succ (Succ (Succ Zero)))) Nil)) (Cons (Succ (Succ (Succ Zero))) Nil).

Compute lfind_eval  (Cons (Succ Zero) Nil) (Cons (Succ (Succ (Succ Zero))) (Cons (Succ (Succ Zero)) (Cons Zero (Cons Zero (Cons (Succ Zero) Nil))))).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Cons Zero Nil) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Nil) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Cons Zero Nil) (Cons (Succ Zero) Nil).

Compute lfind_eval  (Nil) (Nil).

Compute lfind_eval  (Nil) (Nil).


Require Import coqrel.LogicalRelations.
Require Import structures.Lattice.

(** We construct various kinds of strategy models by defining the
  plays they use and a corresponding prefix ordering, then choosing
  a free completion corresponding to the kind of nondeterminism we
  wish to consider.

  In particular, the traditional construction of strategies as
  prefix-closed sets of plays corresponds to the downset completion,
  which is initial in the category of distributive lattices and
  join-distributive morphisms. This introduces angelic nondeterminism,
  which lets us consider all possible choices of the environment.
  We go one step further and consider the free completely distributive
  lattice over plays, which is initial wrt. complete morphisms. This
  models demonic as well as angelic nondeterminism and allows us to
  model strategy specifications permitting several possible system
  behaviors.

  This library captures the general pattern poset completions
  definitions as a module type and proves general properties which
  hold in all of them. This allows parts of our development to be
  carried out in a modular way and be instantiated for arbitrary
  lattice completions. *)

(** * Poset completions *)

(** Each of the completions we will consider is a free completion for
  a specific category of completely distributive lattices. Hence, the
  first step when constructing a completion procedure is to specify
  the kind of morphisms used in that category. *)

Module Type LatticeCategory.

  Parameter Morphism :
    forall {L M : cdlattice}, (L -> M) -> Prop.

  Axiom mor_ref :
    forall {L M : cdlattice} (f : L -> M), Morphism f -> PosetMorphism f.

  Axiom id_mor :
    forall {L : cdlattice}, @Morphism L L (fun l => l).

  Axiom compose_mor :
    forall {A B C : cdlattice} (g : B -> C) (f : A -> B),
      Morphism f -> Morphism g -> Morphism (fun a => g (f a)).

  Existing Class Morphism.
  Existing Instance mor_ref.
  Existing Instance id_mor.
  Existing Instance compose_mor.

End LatticeCategory.

(** Then a free completion has the following interface. Note that the
  type of morphism used fully characterizes the completion, so that we
  can always use an opaque implementation. *)

Module Type LatticeCompletionSpec (LC : LatticeCategory).

  Parameter F : poset -> cdlattice.
  Parameter emb : forall {C : poset}, C -> F C.
  Parameter ext : forall {C : poset} {L : cdlattice}, (C -> L) -> F C -> L.

  Section DEFS.
    Context {C : poset} {L : cdlattice} {f : C -> L}.

    Axiom emb_mor : forall c1 c2 : C, emb c1 [= emb c2 <-> c1 [= c2.
    Axiom ext_mor : LC.Morphism (ext f).
    Axiom ext_ana : forall `{Hf : !PosetMorphism f} x, ext f (emb x) = f x.
    Axiom ext_unique :
      forall `{Hf : !PosetMorphism f} (g : F C -> L) `{Hg : !LC.Morphism g},
        (forall x, g (emb x) = f x) ->
        (forall x, g x = ext f x).
  End DEFS.

  Hint Extern 1 (LC.Morphism (ext _)) =>
    apply @ext_mor : typeclass_instances.

End LatticeCompletionSpec.

Module LatticeCompletionDefs (LC : LatticeCategory) (CS : LatticeCompletionSpec LC).

  Definition map {A B : poset} (f : A -> B) : CS.F A -> CS.F B :=
    CS.ext (fun a => CS.emb (f a)).

  Instance map_mor {A B : poset} (f : A -> B) :
    PosetMorphism f ->
    LC.Morphism (map f).
  Proof.
    unfold map.
    typeclasses eauto.
  Qed.

  Instance emb_mor' {C : poset} :
    PosetMorphism (CS.emb (C:=C)).
  Proof.
    constructor. intros x y Hxy.
    apply CS.emb_mor. auto.
  Qed.

  Lemma ext_emb {A : poset} (x : CS.F A) :
    CS.ext CS.emb x = x.
  Proof.
  Admitted.

  Lemma ext_ext {A B : poset} {L : cdlattice} :
    forall {f : A -> CS.F B} `{!PosetMorphism f},
    forall {g : B -> L} `{!PosetMorphism g},
    forall (x : CS.F A), CS.ext g (CS.ext f x) = CS.ext (fun a => CS.ext g (f a)) x.
  Proof.
  Admitted.

  Global Instance emb_params : Params (@CS.emb) 1.
  Global Instance ext_params : Params (@CS.ext) 1.
  Global Instance map_params : Params (@map) 1.

End LatticeCompletionDefs.

Module Type LatticeCompletion (LC : LatticeCategory) :=
  LatticeCompletionSpec LC <+ LatticeCompletionDefs LC.


Require Import HoTT.
Require Import HoTT.Categories.Functor.
Require Import GR.bicategories.bicategories.
Require Import GR.bicategories.lax_functors.
Require Import GR.bicategories.lax_transformations.
From GR.groupoid Require Import
     groupoid_quotient.gquot
     groupoid_quotient.gquot_functor
     groupoid_quotient.gquot_principles
     grpd_bicategory.grpd_bicategory
     path_groupoid.path_groupoid.
From GR.basics Require Import
     general.

Section CounitInverse.
  Context `{Univalence}.

  Definition counit_inv_map (A : 1 -Type)
    : one_types⟦A,gquot_functor(path_groupoid A)⟧
    := gcl (path_groupoid A).

  Definition counit_gq_inv_d
    : PseudoTransformation_d
        (lax_id_functor one_types)
        (lax_comp gquot_functor path_groupoid_functor).
  Proof.
    make_pseudo_transformation.
    - exact counit_inv_map.
    - reflexivity.
    - reflexivity.
  Defined.

  Definition counit_gq_inv_is_lax
    : is_pseudo_transformation_p counit_gq_inv_d.
  Proof.
    make_is_pseudo_transformation.
    - intros X Y f g α.
      induction α ; cbn.
      rewrite concat_1p, concat_p1.
      f_ap.
      funext x.
      rewrite ap10_path_forall ; simpl.
      rewrite ge.
      reflexivity.
    - intros X.
      cbn.
      rewrite !concat_1p, concat_p1.
      f_ap.
      funext x.
      rewrite <- path_forall_pp.
      rewrite ap10_path_forall ; simpl.
      rewrite ge.
      reflexivity.
    - intros X Y Z f g.
      cbn.
      rewrite !concat_1p, !concat_p1.
      rewrite <- !path_forall_pp.
      f_ap.
      funext x.
      rewrite ap10_path_forall.
      simpl.
      rewrite ge.
      reflexivity.
    - reflexivity.
    - reflexivity.
  Qed.

  Definition counit_inv
    : LaxTransformation
        (lax_id_functor one_types)
        (lax_comp gquot_functor path_groupoid_functor)
    := Build_PseudoTransformation counit_gq_inv_d counit_gq_inv_is_lax.

  Global Instance counit_inv_pseudo
    : is_pseudo_transformation counit_inv
    := _.
End CounitInverse.


Require Import List.
Import ListNotations.
Require Import Sumbool.

Ltac break_and :=
  repeat match goal with
           | [H : _ /\ _ |- _ ] => destruct H
         end.

Ltac break_if :=
  match goal with
    | [ |- context [ if ?X then _ else _ ] ] =>
      match type of X with
        | sumbool _ _ => destruct X
        | _ => destruct X eqn:?
      end
  end.

Definition update2 {A B : Type} (A_eq_dec : forall x y : A, {x = y} + {x <> y}) (f : A -> A -> B) (x y : A) (v : B) :=
  fun x' y' => if sumbool_and _ _ _ _ (A_eq_dec x x') (A_eq_dec y y') then v else f x' y'.

Fixpoint collate {A B : Type} (A_eq_dec : forall x y : A, {x = y} + {x <> y}) (from : A) (f : A -> A -> list B) (ms : list (A * B)) :=
  match ms with
   | [] => f
   | (to, m) :: ms' => collate A_eq_dec from (update2 A_eq_dec f from to (f from to ++ [m])) ms'
  end.

Section Update2.
  Variables A B : Type.
  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.

  Lemma collate_neq :
    forall h n n' ns (f : A -> A -> list B),
      h <> n ->
      collate A_eq_dec h f ns n n' = f n n'.
  Proof using.
    intros.
    revert f.
    induction ns; intros; auto.
    destruct a.
    simpl in *.
    rewrite IHns.
    unfold update2.
    break_if; auto.
    break_and; subst.
    intuition.
  Qed.
End Update2.