(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

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

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

Require Import Decidable Setoid DecidableTypeEx FSetFacts.

(** First, a version for Weak Sets in functorial presentation *)

Module WDecide_fun (E : DecidableType)(Import M : WSfun E).
 Module F := FSetFacts.WFacts_fun E M.

(** * 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.
    Export Decidable.
    Export Setoid.

    (** ** Lemmas and Tactics About Decidable Propositions *)

    (** ** 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. *)

    (** ** 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, dealing
        with multiples rewrite sites and side-conditions is
        done more cleverly with the following explicit
        analysis of goals. *)

    Ltac or_not_l_iff P Q tac :=
      (rewrite (or_not_l_iff_1 P Q) by tac) ||
      (rewrite (or_not_l_iff_2 P Q) by tac).

    Ltac or_not_r_iff P Q tac :=
      (rewrite (or_not_r_iff_1 P Q) by tac) ||
      (rewrite (or_not_r_iff_2 P Q) by tac).

    Ltac or_not_l_iff_in P Q H tac :=
      (rewrite (or_not_l_iff_1 P Q) in H by tac) ||
      (rewrite (or_not_l_iff_2 P Q) in H by tac).

    Ltac or_not_r_iff_in P Q H tac :=
      (rewrite (or_not_r_iff_1 P Q) in H by tac) ||
      (rewrite (or_not_r_iff_2 P Q) in H by tac).

    Tactic Notation "push" "not" "using" ident(db) :=
      let dec := solve_decidable using db in
      unfold not, iff;
      repeat (
        match goal with
        | |- context [True -> False] => rewrite not_true_iff
        | |- context [False -> False] => rewrite not_false_iff
        | |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
        | |- context [(?P -> False) -> (?Q -> False)] =>
            rewrite (contrapositive P Q) by dec
        | |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
        | |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
        | |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
        | |- context [?P \/ ?Q -> False] => rewrite (not_or_iff P Q)
        | |- context [?P /\ ?Q -> False] => rewrite (not_and_iff P Q)
        | |- context [(?P -> ?Q) -> False] => rewrite (not_imp_iff P Q) by dec
        end);
      fold any not.

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

    Tactic Notation
      "push" "not" "in" "*" "|-" "using" ident(db) :=
      let dec := solve_decidable using db in
      unfold not, iff in * |-;
      repeat (
        match goal with
        | H: context [True -> False] |- _ => rewrite not_true_iff in H
        | H: context [False -> False] |- _ => rewrite not_false_iff in H
        | H: context [(?P -> False) -> False] |- _ =>
          rewrite (not_not_iff P) in H by dec
        | H: context [(?P -> False) -> (?Q -> False)] |- _ =>
          rewrite (contrapositive P Q) in H by dec
        | H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
        | H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
        | H: context [(?P -> False) -> ?Q] |- _ =>
          rewrite (imp_not_l P Q) in H by dec
        | H: context [?P \/ ?Q -> False] |- _ => rewrite (not_or_iff P Q) in H
        | H: context [?P /\ ?Q -> False] |- _ => rewrite (not_and_iff P Q) in H
        | H: context [(?P -> ?Q) -> False] |- _ =>
          rewrite (not_imp_iff P Q) in H by dec
        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) \/ (Q -> R))) ->
      (~ (P /\ R)) ->
      (~ (P -> R)) ->
      True.
    Proof.
      intros. push not in *.
       (* note that ~(R->P) remains (since R isnt decidable) *)
      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) :=
      let dec := solve_decidable using db in
      unfold not, iff;
      repeat (
        match goal with
        | |- context [True -> False] => rewrite not_true_iff
        | |- context [False -> False] => rewrite not_false_iff
        | |- context [(?P -> False) -> False] => rewrite (not_not_iff P) by dec
        | |- context [(?P -> False) -> (?Q -> False)] =>
          rewrite (contrapositive P Q) by dec
        | |- context [(?P -> False) \/ ?Q] => or_not_l_iff P Q dec
        | |- context [?P \/ (?Q -> False)] => or_not_r_iff P Q dec
        | |- context [(?P -> False) -> ?Q] => rewrite (imp_not_l P Q) by dec
        | |- context [(?P -> False) /\ (?Q -> False)] =>
          rewrite <- (not_or_iff P Q)
        | |- context [?P -> ?Q -> False] => rewrite <- (not_and_iff P Q)
        | |- context [?P /\ (?Q -> False)] => rewrite <- (not_imp_iff P Q) by dec
        | |- context [(?Q -> False) /\ ?P] =>
          rewrite <- (not_imp_rev_iff P Q) by dec
        end);
      fold any not.

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

    Tactic Notation
      "pull" "not" "in" "*" "|-" "using" ident(db) :=
      let dec := solve_decidable using db in
      unfold not, iff in * |-;
      repeat (
        match goal with
        | H: context [True -> False] |- _ => rewrite not_true_iff in H
        | H: context [False -> False] |- _ => rewrite not_false_iff in H
        | H: context [(?P -> False) -> False] |- _ =>
          rewrite (not_not_iff P) in H by dec
        | H: context [(?P -> False) -> (?Q -> False)] |- _ =>
          rewrite (contrapositive P Q) in H by dec
        | H: context [(?P -> False) \/ ?Q] |- _ => or_not_l_iff_in P Q H dec
        | H: context [?P \/ (?Q -> False)] |- _ => or_not_r_iff_in P Q H dec
        | H: context [(?P -> False) -> ?Q] |- _ =>
          rewrite (imp_not_l P Q) in H by dec
        | H: context [(?P -> False) /\ (?Q -> False)] |- _ =>
          rewrite <- (not_or_iff P Q) in H
        | H: context [?P -> ?Q -> False] |- _ =>
          rewrite <- (not_and_iff P Q) in H
        | H: context [?P /\ (?Q -> False)] |- _ =>
          rewrite <- (not_imp_iff P Q) in H by dec
        | H: context [(?Q -> False) /\ ?P] |- _ =>
          rewrite <- (not_imp_rev_iff P Q) in H by dec
        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) /\ ~ (Q -> R)) ->
      (~ 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. *)

    (** remove logical hypothesis inter-dependencies (fix #2136). *)

    Ltac no_logical_interdep :=
      match goal with
        | H : ?P |- _ =>
          match type of P with
            | Prop =>
              match goal with H' : context [ H ] |- _ => clear dependent H' end
            | _ => fail
          end; no_logical_interdep
        | _ => idtac
      end.

    Ltac abstract_term t :=
      tryif (is_var t) then fail "no need to abstract a variable"
      else (let x := fresh "x" in set (x := t) in *; try clearbody x).

    Ltac abstract_elements :=
      repeat
        (match goal with
           | |- context [ singleton ?t ] => abstract_term t
           | _ : context [ singleton ?t ] |- _ => abstract_term t
           | |- context [ add ?t _ ] => abstract_term t
           | _ : context [ add ?t _ ] |- _ => abstract_term t
           | |- context [ remove ?t _ ] => abstract_term t
           | _ : context [ remove ?t _ ] |- _ => abstract_term t
           | |- context [ In ?t _ ] => abstract_term t
           | _ : context [ In ?t _ ] |- _ => abstract_term t
         end).

    (** [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 *.

    (** [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 : Type) (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 :=
      repeat (
        match goal with
        | H : context [ @Logic.eq ?T ?x ?y ] |- _ =>
          tryif (change T with E.t in H) then fail
          else tryif (change T with t in H) then fail
          else clear H
        | H : ?P |- _ =>
          tryif 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].
        *)

    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.

    Lemma eq_refl_iff (x : E.t) : E.eq x x <-> True.
    Proof.
     now split.
    Qed.

    Hint Rewrite eq_refl_iff : set_eq_simpl.

    (** ** Decidability of FSet Propositions *)

    (** [In] is decidable. *)
    Lemma dec_In : forall x s,
      decidable (In x s).
    Proof.
      red; intros; generalize (F.mem_iff s x); case (mem x s); intuition.
    Qed.

    (** [E.eq] is decidable. *)
    Lemma dec_eq : forall (x y : E.t),
      decidable (E.eq x y).
    Proof.
      red; intros x y; destruct (E.eq_dec 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 )
        | H : forall x : ?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 ?x |- _ => clear H
        | H: E.eq ?x ?y |- _ => rewrite H in *; clear H
        end);
      autorewrite with set_eq_simpl in *.

    (** ** 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 := 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 :=
      autorewrite with set_eq_simpl in *;
      inst_FSet_hypotheses;
      autorewrite with set_simpl set_eq_simpl in *;
      push not in * using FSet_decidability;
      substFSet;
      assert_decidability;
      auto;
      (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;
    (** We don't care about the value of elements : complex ones are
        abstracted as new variables (avoiding potential dependencies,
        see bug #2464) *)
    abstract_elements;
    (** We remove dependencies to logical hypothesis. This way,
        later "clear" will work nicely (see bug #2136) *)
    no_logical_interdep;
    (** 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 [=] is in
        the context is with [subst], so we will try that first.
        In fact, we may as well convert uses of [E.eq] into [=]
        when possible before we do [subst] so that we can 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 =>
      contradict H; fsetdec_body
    | H: (In ?x ?r) -> False |- (E.eq ?x ?y) -> False =>
      contradict H; fsetdec_body
    | H: (In ?x ?r) -> False |- (E.eq ?y ?x) -> False =>
      contradict H; fsetdec_body
    | H: ?P -> False |- ?Q -> False =>
      tryif prop (FSet_elt_Prop P) holds by
        (auto 100 with FSet_Prop)
      then (contradict 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_add_In : forall x y s,
      In x (add y s) ->
      ~ E.eq x y ->
      In x s.
    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.

    Lemma test_baydemir :
      forall (f : t -> t),
      forall (s : t),
      forall (x y : elt),
      In x (add y (f s)) ->
      ~ E.eq x y ->
      In x (f s).
    Proof.
      fsetdec.
    Qed.

  End FSetDecideTestCases.

End WDecide_fun.

Require Import FSetInterface.

(** Now comes variants for self-contained weak sets and for full sets.
    For these variants, only one argument is necessary. Thanks to
    the subtyping [WS<=S], the [Decide] functor which is meant to be
    used on modules [(M:S)] can simply be an alias of [WDecide]. *)

Module WDecide (M:WS) := !WDecide_fun M.E M.
Module Decide := WDecide.


(* http://d.hatena.ne.jp/hzkr/20100902 *)

Goal forall P Q: Prop, (P -> Q) -> P -> Q.
Proof.
  intros.  (* 全部剥がす *)
  apply H.
  exact H0.  (* apply H0 でも同じ *)
Qed.

Goal forall P Q: Prop, (P -> Q) -> P -> Q.
Proof.
  intros p q f.  (* 名前の数だけ剥がす *)
  assumption.  (* exact f でも同じ *)
Qed.

Goal forall P Q: Prop, (P -> Q) -> P -> Q.
Proof.
  exact (fun p q f x => f x).
Qed.


(*
Copyright © 2008 Russell O’Connor

Permission is hereby granted, free of charge, to any person obtaining a copy of
this proof and associated documentation files (the "Proof"), to deal in
the Proof without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Proof, and to permit persons to whom the Proof is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Proof.

THE PROOF IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE PROOF OR THE USE OR OTHER DEALINGS IN THE PROOF.
*)
Require Import CoRN.model.totalorder.QposMinMax.
Require Export CoRN.metric2.Metric.

Local Open Scope Q_scope.

(**
** Classification of metric spaces

A metric space is located if you can choose
between ball d x y and ~ball e x y for e < d. Every located metric
is a stable metric. This translates the located property of the real
numbers e < d -> (e < d(x,y) \/ d(x,y) < d). *)
Definition locatedMetric (ms:MetricSpace) :=
  forall (e d:Q) (x y:ms),
    e < d -> {ball d x y}+{~ball e x y}.

(** At the top level a metric space is decidable if its ball relation
is decidable.  Every decidable metric is a located metric. *)
Definition decidableMetric (ms:MetricSpace) :=
 forall e (x y:ms), {ball e x y}+{~ball e x y}.

Lemma decidable_located : forall ms,
 decidableMetric ms -> locatedMetric ms.
Proof.
 intros ms H e d x y Hed.
 destruct (H e x y).
  left.
  abstract ( apply ball_weak_le with e;
             try assumption; apply Qlt_le_weak; assumption).
 right; assumption.
Defined.


Require Import Gappa_common.
Require Import Gappa_decimal.

Definition Float1 := Z2R.

Definition constant2_helper (x : float2) (zi : FF) :=
 Fle2 (lower zi) x && Fle2 x (upper zi).

Theorem constant2 :
 forall x : float2, forall zi : FF,
 constant2_helper x zi = true ->
 BND x zi.
Proof.
intros x zi Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
split ; assumption.
Qed.

Theorem constant1 :
 forall x : Z, forall zi : FF,
 constant2_helper (Float2 x 0) zi = true ->
 BND (Float1 x) zi.
Proof.
intros x zi Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
rewrite <- (Rmult_1_r (Float1 x)).
change (Float1 x * 1)%R with (float2R (Float2 x 0)).
split ; assumption.
Qed.

Definition constant10_helper (x : float10) (zi : FF) :=
 Dle_fd (lower zi) x && Dle_df x (upper zi).

Theorem constant10 :
 forall x : float10, forall zi : FF,
 constant10_helper x zi = true ->
 BND x zi.
Proof.
intros x zi Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Dle_fd_correct _ _ H1). clear H1. intro H1.
generalize (Dle_df_correct _ _ H2). clear H2. intro H2.
split ; assumption.
Qed.

Definition subset_helper (xi zi : FF) :=
 Fle2 (lower zi) (lower xi) &&
 Fle2 (upper xi) (upper zi).

Theorem subset :
 forall x : R, forall xi zi : FF,
 BND x xi ->
 subset_helper xi zi = true ->
 BND x zi.
Proof.
intros x xi zi Hx Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
apply IRsubset with (1 := H1) (2 := H2) (3 := Hx).
Qed.

Theorem subset_l :
 forall x : R, forall xi : FF, forall f : float2,
 BND x xi ->
 Fle2 f (lower xi) = true ->
 (f <= x)%R.
Proof.
intros x xi f Hx Hb.
generalize (Fle2_correct _ _ Hb). clear Hb. intro H1.
apply Rle_trans with (1 := H1).
exact (proj1 Hx).
Qed.

Theorem subset_r :
 forall x : R, forall xi : FF, forall f : float2,
 BND x xi ->
 Fle2 (upper xi) f = true ->
 (x <= f)%R.
Proof.
intros x xi f Hx Hb.
generalize (Fle2_correct _ _ Hb). clear Hb. intro H1.
apply Rle_trans with (2 := H1).
exact (proj2 Hx).
Qed.

Definition intersect_helper (xf yf : float2) (zi : FF) :=
 Fle2 (lower zi) yf &&
 Fle2 xf (upper zi).

Theorem intersect :
 forall z : R, forall xi yi zi : FF,
 BND z xi -> BND z yi ->
 intersect_helper (upper xi) (lower yi) zi = true ->
 BND z zi.
Proof.
intros z xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
split.
apply Rle_trans with (1 := H1) (2 := (proj1 Hy)).
apply Rle_trans with (1 := (proj2 Hx)) (2 := H2).
Qed.

Theorem intersect_hb :
 forall z : R, forall xf : float2, forall yi zi : FF,
 (z <= xf)%R -> BND z yi ->
 intersect_helper xf (lower yi) zi = true ->
 BND z zi.
Proof.
intros z xf yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
split.
apply Rle_trans with (1 := H1) (2 := (proj1 Hy)).
apply Rle_trans with (1 := Hx) (2 := H2).
Qed.

Theorem intersect_bh :
 forall z : R, forall yf : float2, forall xi zi : FF,
 BND z xi -> (yf <= z)%R ->
 intersect_helper (upper xi) yf zi = true ->
 BND z zi.
Proof.
intros z yf xi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
split.
apply Rle_trans with (1 := H1) (2 := Hy).
apply Rle_trans with (1 := (proj2 Hx)) (2 := H2).
Qed.

Theorem intersect_hh :
  forall z : R, forall xf yf : float2, forall zi : FF,
  (z <= xf)%R -> (yf <= z)%R ->
  intersect_helper xf yf zi = true ->
  BND z zi.
Proof.
intros z xf yf zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
apply Fle2_correct in H1.
apply Fle2_correct in H2.
split.
apply Rle_trans with (1 := H1) (2 := Hy).
apply Rle_trans with (1 := Hx) (2 := H2).
Qed.

Theorem absurd_intersect :
 forall z : R, forall xi yi : FF,
 BND z xi -> BND z yi ->
 Flt2 (upper xi) (lower yi) = true ->
 False.
Proof.
intros z xi yi Hx Hy Hb.
generalize (Flt2_correct _ _ Hb). clear Hb. intro H.
generalize (Rle_lt_trans _ _ _ (proj2 Hx) H). clear H. intro H.
generalize (Rlt_le_trans _ _ _ H (proj1 Hy)). clear H. intro H.
elim (Rlt_irrefl _ H).
Qed.

Theorem absurd_intersect_hb :
 forall z : R, forall xf : float2, forall yi : FF,
 (z <= xf)%R -> BND z yi ->
 Flt2 xf (lower yi) = true ->
 False.
Proof.
intros z xi yi Hx Hy Hb.
generalize (Flt2_correct _ _ Hb). clear Hb. intro H.
generalize (Rle_lt_trans _ _ _ Hx H). clear H. intro H.
generalize (Rlt_le_trans _ _ _ H (proj1 Hy)). clear H. intro H.
elim (Rlt_irrefl _ H).
Qed.

Theorem absurd_intersect_bh :
 forall z : R, forall xi : FF, forall yf : float2,
 BND z xi -> (yf <= z)%R ->
 Flt2 (upper xi) yf = true ->
 False.
Proof.
intros z xi yi Hx Hy Hb.
generalize (Flt2_correct _ _ Hb). clear Hb. intro H.
generalize (Rle_lt_trans _ _ _ (proj2 Hx) H). clear H. intro H.
generalize (Rlt_le_trans _ _ _ H Hy). clear H. intro H.
elim (Rlt_irrefl _ H).
Qed.

Theorem union :
  forall (x : R) (xl : float2) (P : Prop),
  (Rle x xl -> P) ->
  (Rle xl x -> P) ->
  P.
Proof.
intros x xl P H1 H2.
destruct (Rlt_le_dec x xl) as [H|H].
apply H1.
now apply Rlt_le.
now apply H2.
Qed.

Theorem union' :
  forall (x : R) (xi : FF) (P : Prop),
  (BND x xi -> P) ->
  (Rle (upper xi) x -> P) ->
  Rle (lower xi) x -> P.
Proof.
intros x xi P H1 H2 Hx.
destruct (Rlt_le_dec x (upper xi)) as [H|H].
apply H1.
apply (conj Hx).
now apply Rlt_le.
now apply H2.
Qed.

Definition eql_of_cst_helper (xi yi : FF) :=
  Feq2 (lower xi) (upper yi) &&
  Feq2 (upper xi) (lower yi).

Theorem eql_of_cst :
  forall x y : R, forall xi yi : FF,
  BND x xi -> BND y yi ->
  eql_of_cst_helper xi yi = true ->
  x = y.
Proof.
intros x y xi yi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Feq2_correct _ _ H1). clear H1. intro H1.
generalize (Feq2_correct _ _ H2). clear H2. intro H2.
apply Rle_antisym.
apply Rle_trans with (1 := proj2 Hx).
rewrite H2.
apply Hy.
apply Rle_trans with (1 := proj2 Hy).
rewrite <- H1.
apply Hx.
Qed.

Definition neg_helper (xi zi : FF) :=
 Fle2 (lower zi) (Fopp2 (upper xi)) &&
 Fle2 (Fopp2 (lower xi)) (upper zi).

Theorem neg :
 forall x : R, forall xi zi : FF,
 BND x xi ->
 neg_helper xi zi = true ->
 BND (-x) zi.
Proof.
intros x xi zi Hx Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). rewrite Fopp2_correct. clear H1. intro H1.
generalize (Fle2_correct _ _ H2). rewrite Fopp2_correct. clear H2. intro H2.
apply IRopp with (1 := H1) (2 := H2) (3 := Hx).
Qed.

Definition add_helper (xi yi zi : FF) :=
 Fle2 (lower zi) (Fplus2 (lower xi) (lower yi)) &&
 Fle2 (Fplus2 (upper xi) (upper yi)) (upper zi).

Theorem add :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 add_helper xi yi zi = true ->
 BND (x + y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). rewrite Fplus2_correct. clear H1. intro H1.
generalize (Fle2_correct _ _ H2). rewrite Fplus2_correct. clear H2. intro H2.
apply IRplus with (1 := H1) (2 := H2) (3 := Hx) (4 := Hy).
Qed.

Definition sub_helper (xi yi zi : FF) :=
 Fle2 (lower zi) (Fminus2 (lower xi) (upper yi)) &&
 Fle2 (Fminus2 (upper xi) (lower yi)) (upper zi).

Theorem sub :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 sub_helper xi yi zi = true ->
 BND (x - y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). rewrite Fminus2_correct. clear H1. intro H1.
generalize (Fle2_correct _ _ H2). rewrite Fminus2_correct. clear H2. intro H2.
apply IRminus with (1 := H1) (2 := H2) (3 := Hx) (4 := Hy).
Qed.

Definition not_zero (zi : FF) :=
 Fpos (lower zi) || Fneg (upper zi).

Lemma not_zero_correct :
 forall z : R, forall zi : FF,
 BND z zi ->
 not_zero zi = true ->
 (z <> 0)%R.
Proof.
intros z zi Hz Hb.
apply Rlt_dichotomy_converse.
generalize (orb_prop _ _ Hb). clear Hb.
intro H. elim H; clear H; intro H.
right.
generalize (Fpos_correct _ H). clear H. intro H.
unfold Rgt.
apply Rlt_le_trans with (1 := H).
exact (proj1 Hz).
left.
generalize (Fneg_correct _ H). clear H. intro H.
apply Rle_lt_trans with (2 := H).
exact (proj2 Hz).
Qed.

Definition contains_zero_helper (zi : FF) :=
 Fneg0 (lower zi) &&
 Fpos0 (upper zi).

Lemma contains_zero :
 forall zi : FF,
 contains_zero_helper zi = true ->
 BND 0 zi.
Proof.
intros zi Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg0_correct _ H1). clear H1. intro H1.
generalize (Fpos0_correct _ H2). clear H2. intro H2.
split ; assumption.
Qed.

Lemma sub_refl :
 forall x : R, forall zi : FF,
 contains_zero_helper zi = true ->
 BND (x - x) zi.
Proof.
intros x zi Hb.
unfold Rminus.
rewrite (Rplus_opp_r x).
apply contains_zero with (1 := Hb).
Qed.

Lemma sub_of_eql :
  forall x y : R, forall zi : FF,
  x = y ->
  contains_zero_helper zi = true ->
  BND (x - y) zi.
Proof.
intros x y zi E Hb.
unfold Rminus.
rewrite E, Rplus_opp_r.
apply contains_zero with (1 := Hb).
Qed.

Definition div_refl_helper (zi : FF) :=
 Fle2 (lower zi) (Float2 1 0) &&
 Fle2 (Float2 1 0) (upper zi).

Lemma div_refl :
 forall x : R, forall zi : FF,
 NZR x ->
 div_refl_helper zi = true ->
 BND (x / x) zi.
Proof.
intros x zi Hx Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
assert (Float2 1 0 = 1 :>R)%R.
apply Rmult_1_r.
generalize (Fle2_correct _ _ H1). clear H1. rewrite H. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. rewrite H. intro H2.
unfold Rdiv.
rewrite Rinv_r. 2: exact Hx.
exact (conj H1 H2).
Qed.

Definition mul_pp_helper (xi yi zi : FF) :=
 Fpos0 (lower xi) &&
 Fpos0 (lower yi) &&
 Fle2 (lower zi) (Fmult2 (lower xi) (lower yi)) &&
 Fle2 (Fmult2 (upper xi) (upper yi)) (upper zi).

Theorem mul_pp :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_pp_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos0_correct _ H1). clear H1. intro H1.
generalize (Fpos0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRmult_pp with (1 := H1) (2 := H2) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition mul_pn_helper (xi yi zi : FF) :=
 Fpos0 (lower xi) &&
 Fneg0 (upper yi) &&
 Fle2 (lower zi) (Fmult2 (upper xi) (lower yi)) &&
 Fle2 (Fmult2 (lower xi) (upper yi)) (upper zi).

Theorem mul_pn :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_pn_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos0_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRmult_pn with (1 := H1) (2 := H2) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition mul_np_helper (xi yi zi : FF) := mul_pn_helper yi xi zi.

Theorem mul_np :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_np_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
rewrite Rmult_comm.
exact (mul_pn _ _ _ _ _ Hy Hx Hb).
Qed.

Definition mul_nn_helper (xi yi zi : FF) :=
 Fneg0 (upper xi) &&
 Fneg0 (upper yi) &&
 Fle2 (lower zi) (Fmult2 (upper xi) (upper yi)) &&
 Fle2 (Fmult2 (lower xi) (lower yi)) (upper zi).

Theorem mul_nn :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_nn_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg0_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRmult_nn with (1 := H1) (2 := H2) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition mul_po_helper (xi yi zi : FF) :=
 Fpos0 (lower xi) &&
 Fneg0 (lower yi) && Fpos0 (upper yi) &&
 Fle2 (lower zi) (Fmult2 (upper xi) (lower yi)) &&
 Fle2 (Fmult2 (upper xi) (upper yi)) (upper zi).

Theorem mul_po :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_po_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H5).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos0_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fpos0_correct _ H3). clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
generalize (Fle2_correct _ _ H5). rewrite Fmult2_correct. clear H5. intro H5.
apply IRmult_po with (1 := H1) (2 := H2) (3 := H3) (4 := H4) (5 := H5) (6 := Hx) (7 := Hy).
Qed.

Definition mul_op_helper (xi yi zi : FF) := mul_po_helper yi xi zi.

Theorem mul_op :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_po_helper yi xi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
rewrite Rmult_comm.
exact (mul_po _ _ _ _ _ Hy Hx Hb).
Qed.

Definition mul_no_helper (xi yi zi : FF) :=
 Fneg0 (upper xi) &&
 Fneg0 (lower yi) && Fpos0 (upper yi) &&
 Fle2 (lower zi) (Fmult2 (lower xi) (upper yi)) &&
 Fle2 (Fmult2 (lower xi) (lower yi)) (upper zi).

Theorem mul_no :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_no_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H5).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg0_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fpos0_correct _ H3). clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
generalize (Fle2_correct _ _ H5). rewrite Fmult2_correct. clear H5. intro H5.
apply IRmult_no with (1 := H1) (2 := H2) (3 := H3) (4 := H4) (5 := H5) (6 := Hx) (7 := Hy).
Qed.

Definition mul_on_helper (xi yi zi : FF) := mul_no_helper yi xi zi.

Theorem mul_on :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_no_helper yi xi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
rewrite Rmult_comm.
exact (mul_no _ _ _ _ _ Hy Hx Hb).
Qed.

Definition mul_oo_helper (xi yi zi : FF) :=
 Fneg0 (lower xi) && Fpos0 (upper xi) &&
 Fneg0 (lower yi) && Fpos0 (upper yi) &&
 Fle2 (lower zi) (Fmult2 (lower xi) (upper yi)) &&
 Fle2 (lower zi) (Fmult2 (upper xi) (lower yi)) &&
 Fle2 (Fmult2 (lower xi) (lower yi)) (upper zi) &&
 Fle2 (Fmult2 (upper xi) (upper yi)) (upper zi).

Theorem mul_oo :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 mul_oo_helper xi yi zi = true ->
 BND (x * y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H8).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H7).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H6).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H5).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg0_correct _ H1). clear H1. intro H1.
generalize (Fpos0_correct _ H2). clear H2. intro H2.
generalize (Fneg0_correct _ H3). clear H3. intro H3.
generalize (Fpos0_correct _ H4). clear H4. intro H4.
generalize (Fle2_correct _ _ H5). rewrite Fmult2_correct. clear H5. intro H5.
generalize (Fle2_correct _ _ H6). rewrite Fmult2_correct. clear H6. intro H6.
generalize (Fle2_correct _ _ H7). rewrite Fmult2_correct. clear H7. intro H7.
generalize (Fle2_correct _ _ H8). rewrite Fmult2_correct. clear H8. intro H8.
exact (IRmult_oo _ _ _ _ _ _ H1 H2 H3 H4 H6 H5 H7 H8 _ _ Hx Hy).
Qed.

Definition square_helper (xi zi : FF) :=
 Fle2 (lower zi) (Fmult2 (lower xi) (lower xi)) &&
 Fle2 (Fmult2 (upper xi) (upper xi)) (upper zi).

Theorem square :
  forall x : R, forall xi zi : FF,
  ABS x xi ->
  square_helper xi zi = true ->
  BND (x * x) zi.
Proof.
intros x xi zi (Hx1,Hx2) Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
fold (Rsqr x).
rewrite Rsqr_abs.
apply mul_pp with (1 := Hx2) (2 := Hx2).
unfold mul_pp_helper.
rewrite H1, H2.
apply Fcore_float_prop.F2R_ge_0_reg in Hx1.
revert Hx1.
unfold Fpos0.
case (Fnum (lower xi)) ; [easy|easy|].
intros p H.
now elim H.
Qed.

Definition div_pp_helper (xi yi zi : FF) :=
 Fpos (lower yi) &&
 Fpos0 (lower xi) &&
 Fle2 (Fmult2 (upper yi) (lower zi)) (lower xi) &&
 Fle2 (upper xi) (Fmult2 (lower yi) (upper zi)).

Theorem div_pp :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_pp_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos_correct _ H1). clear H1. intro H1.
generalize (Fpos0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRdiv_pp with (1 := H2) (2 := H1) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition div_op_helper (xi yi zi : FF) :=
 Fpos (lower yi) &&
 Fneg0 (lower xi) && Fpos0 (upper xi) &&
 Fle2 (Fmult2 (lower yi) (lower zi)) (lower xi) &&
 Fle2 (upper xi) (Fmult2 (lower yi) (upper zi)).

Theorem div_op :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_op_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H5).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fpos0_correct _ H3). clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
generalize (Fle2_correct _ _ H5). rewrite Fmult2_correct. clear H5. intro H5.
apply IRdiv_op with (1 := H2) (2 := H3) (3 := H1) (4 := H4) (5 := H5) (6 := Hx) (7 := Hy).
Qed.

Definition div_np_helper (xi yi zi : FF) :=
 Fpos (lower yi) &&
 Fneg0 (upper xi) &&
 Fle2 (Fmult2 (lower yi) (lower zi)) (lower xi) &&
 Fle2 (upper xi) (Fmult2 (upper yi) (upper zi)).

Theorem div_np :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_np_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRdiv_np with (1 := H2) (2 := H1) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition div_pn_helper (xi yi zi : FF) :=
 Fneg (upper yi) &&
 Fpos0 (lower xi) &&
 Fle2 (upper xi) (Fmult2 (upper yi) (lower zi)) &&
 Fle2 (Fmult2 (lower yi) (upper zi)) (lower xi).

Theorem div_pn :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_pn_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg_correct _ H1). clear H1. intro H1.
generalize (Fpos0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRdiv_pn with (1 := H2) (2 := H1) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Definition div_on_helper (xi yi zi : FF) :=
 Fneg (upper yi) &&
 Fneg0 (lower xi) && Fpos0 (upper xi) &&
 Fle2 (upper xi) (Fmult2 (upper yi) (lower zi)) &&
 Fle2 (Fmult2 (upper yi) (upper zi)) (lower xi).

Theorem div_on :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_on_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H5).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fpos0_correct _ H3). clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
generalize (Fle2_correct _ _ H5). rewrite Fmult2_correct. clear H5. intro H5.
apply IRdiv_on with (1 := H2) (2 := H3) (3 := H1) (4 := H4) (5 := H5) (6 := Hx) (7 := Hy).
Qed.

Definition div_nn_helper (xi yi zi : FF) :=
 Fneg (upper yi) &&
 Fneg0 (upper xi) &&
 Fle2 (upper xi) (Fmult2 (lower yi) (lower zi)) &&
 Fle2 (Fmult2 (upper yi) (upper zi)) (lower xi).

Theorem div_nn :
 forall x y : R, forall xi yi zi : FF,
 BND x xi -> BND y yi ->
 div_nn_helper xi yi zi = true ->
 BND (x / y) zi.
Proof.
intros x y xi yi zi Hx Hy Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H4).
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fneg_correct _ H1). clear H1. intro H1.
generalize (Fneg0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
generalize (Fle2_correct _ _ H4). rewrite Fmult2_correct. clear H4. intro H4.
apply IRdiv_nn with (1 := H2) (2 := H1) (3 := H3) (4 := H4) (5 := Hx) (6 := Hy).
Qed.

Lemma Rabs_idem :
 forall x : R, (x <= Rabs x)%R.
Proof.
intro x.
unfold Rabs. case Rcase_abs ; intro H.
apply Rle_trans with (1 := (Rlt_le _ _ H)).
auto with real.
apply Req_le.
apply refl_equal.
Qed.

Definition invert_abs_helper (xi zi : FF) :=
 Fle2 (lower zi) (Fopp2 (upper xi)) &&
 Fle2 (upper xi) (upper zi).

Theorem invert_abs :
 forall x : R, forall xi zi : FF,
 BND (Rabs x) xi ->
 invert_abs_helper xi zi = true ->
 BND x zi.
Proof.
intros x xi zi Hx Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fle2_correct _ _ H1). rewrite Fopp2_correct. clear H1. intro H1.
generalize (Fle2_correct _ _ H2). clear H2. intro H2.
split.
apply Rle_trans with (1 := H1).
apply Ropp_le_cancel.
rewrite Ropp_involutive.
apply Rle_trans with (2 := proj2 Hx).
pattern x at 2 ; rewrite <- Ropp_involutive.
rewrite Rabs_Ropp.
apply Rabs_idem.
apply Rle_trans with (2 := H2).
apply Rle_trans with (1 := Rabs_idem x) (2 := proj2 Hx).
Qed.

Definition sqrt_helper (xi zi : FF) :=
 (if (Fneg0 (lower zi)) then Fpos0 (lower xi)
  else Fle2 (Fmult2 (lower zi) (lower zi)) (lower xi)) &&
 Fpos0 (upper zi) &&
 Fle2 (upper xi) (Fmult2 (upper zi) (upper zi)).

Theorem sqrtG:
 forall x : R, forall xi zi : FF,
 BND x xi ->
 sqrt_helper xi zi = true ->
 BND (sqrt x) zi.
Proof.
intros x xi zi Hx Hb.
generalize (andb_prop _ _ Hb). clear Hb. intros (Hb,H3).
generalize (andb_prop _ _ Hb). clear Hb. intros (H1,H2).
generalize (Fpos0_correct _ H2). clear H2. intro H2.
generalize (Fle2_correct _ _ H3). rewrite Fmult2_correct. clear H3. intro H3.
unfold BND.
apply IRsqrt with (2 := H2) (3 := H3) (4 := Hx).
induction (lower zi).
induction Fnum ; simpl in H1.
rewrite float2_zero.
rewrite Rmult_0_l.
assert (H4 := Fpos0_correct _ H1).
case (Rlt_le_dec 0 0) ; intros _ ; exact H4.
case (Rlt_le_dec 0 (Float2 (Zpos p) Fexp)).
intros _.
rewrite <- Fmult2_correct.
apply Fle2_correct.
exact H1.
intro H.
elim (Rlt_irrefl R0).
apply Rlt_le_trans with (2 := H).
apply Fpos_correct.
apply refl_equal.
case (Rlt_le_dec 0 (Float2 (Zneg p) Fexp)).
intro H.
elim (Rlt_irrefl R0).
apply Rlt_trans with (1 := H).
apply Fneg_correct.
apply refl_equal.
intros _.
apply Fpos0_correct.
exact H1.
Qed.

Definition square_rev_helper (xi zi : FF) :=
  Fpos0 (lower zi) && Fpos0 (upper zi) &&
  Fle2 (Fmult2 (lower zi) (lower zi)) (lower xi) &&
  Fle2 (upper xi) (Fmult2 (upper zi) (upper zi)).

Theorem square_rev :
  forall x : R, forall xi zi : FF,
  ABS (x * x) xi ->
  square_rev_helper xi zi = true ->
  ABS x zi.
Proof.
intros x xi zi [Hx1 Hx2] Hb.
apply andb_prop in Hb.
destruct Hb as [Hb H4].
apply andb_prop in Hb.
destruct Hb as [Hb H3].
apply andb_prop in Hb.
destruct Hb as [H1 H2].
apply Fpos0_correct in H1.
apply Fpos0_correct in H2.
apply Fle2_correct in H3.
apply Fle2_correct in H4.
split.
exact H1.
rewrite <- sqrt_Rsqr_abs.
rewrite Rabs_pos_eq in Hx2 by apply Rle_0_sqr.
apply IRsqrt with (2 := H2) (4 := Hx2).
case Rlt_le_dec ; intros H5.
now rewrite <- Fmult2_correct.
exact Hx1.
now rewrite <- Fmult2_correct.
Qed.


Require Import Unicode.Utf8 Program.Tactics Logic.FunctionalExtensionality.
From ctt Require Import Notation.

Require Import ssreflect.
Set Bullet Behavior "Strict Subproofs".
Set Implicit Arguments.

(* True in any topos. *)
Axiom constructive_definite_description :
  forall (A : Type) (P : A → Ω),
    (exists! x, P x)
    →{ x : A | P x }.

Theorem dependent_unique_choice {A B} {R : ∀ x : A, B x → Ω}:
  (forall x:A, exists! y : B x, R x y)
  → (∃ f, ∀ x:A, R x (f x)).
Proof.
  move=> ?.
  eexists => ?.
  apply: proj2_sig.
  by apply: constructive_definite_description.
Qed.

Theorem unique_choice {A B} {R : A → B → Ω}:
  (∀ x:A, exists! y : B, R x y)
  → (∃ f : A → B, ∀ x:A, R x (f x)).
Proof.
  apply: dependent_unique_choice.
Qed.

Axiom propositional_extensionality :
  ∀ (P Q : Ω),
    (P ↔ Q)
    → P = Q.

Theorem binrel_extensionality {T1 T2} {R1 R2 : T1 × T2 → Ω} :
  (∀ x y, R1 (x, y) ↔ R2 (x, y))
  → R1 = R2.
Proof.
  move=> ?.
  apply: functional_extensionality.
  move=> [? ?].
  by apply: propositional_extensionality.
Qed.

Axiom 𝕂 : Type.
Axiom LocalClock : ∃ κ : 𝕂, ⊤.

Module Later.
  Axiom t : 𝕂 → Ω → Ω.
  Axiom cart : ∀ κ (p q : Ω), t κ (p ∧ q) = ((t κ p) ∧ (t κ q)).
  Axiom force : ∀ p, (∀ κ, t κ (p κ)) = (∀ κ, p κ).
  Axiom loeb : ∀ κ p, (t κ p → p) → p.
  Axiom commute_imp : ∀ κ (p q : Ω),  t κ (p → q) = ((t κ p) → (t κ q)).
  Axiom next : ∀ κ (p : Ω), p → t κ p.

  Theorem map : forall κ (p q : Ω), (p → q) → (t κ p → t κ q).
  Proof.
    move=> κ p q f.
    suff H: (t κ p ∧ t κ q) = t κ p.
    - rewrite -H; case; auto.
    - rewrite -cart.
      replace (p ∧ q) with p; auto.
      apply: propositional_extensionality.
      intuition.
  Qed.

  Theorem join : ∀ κ p q, t κ p → t κ q → t κ (p ∧ q).
  Proof.
    move=> *.
    by [rewrite cart].
  Qed.

  Local Ltac elim_aux y :=
    lazymatch goal with
    | H1 : t ?κ _, H2 : t ?κ _ |- _ =>
      let x := fresh in
      have := join H1 H2 => x;
      clear H1; clear H2;
      elim_aux x
    | |- t ?κ _ => refine (map _ y)
  end.

  Ltac gather :=
    lazymatch goal with
    | x : t ?κ _ |- _ => elim_aux x
    | _ => let x := fresh in elim_aux x
    end.

  Axiom Total : Type → Ω.

  Definition Inh (A : Type) : Ω := ∃ x : A, ⊤.

  Axiom yank_existential :
    ∀ A P κ,
      Total A
      → Inh A
      → t κ (∃ x : A, P x)
      → ∃ x : A, t κ (P x).

  Axiom push_existential :
    ∀ A P κ,
      (∃ x : A, t κ (P x))
      → t κ (∃ x : A, P x).

  Axiom push_universal :
    ∀ A P κ,
      (∀ x : A, t κ (P x))
      → t κ (∀ x : A, P x).

  Axiom nat_total : Total nat.
  Theorem nat_inh : Inh nat.
  Proof.
    by exists 0.
  Qed.

  Hint Resolve nat_total nat_inh.

  Theorem commute_eq : ∀ κ (p q : Ω), (t κ p) = (t κ q) → t κ (p = q).
  Proof.
    move=> κ p q H.
    suff: (t κ p) ↔ (t κ q).
    - move=> [H1 H2].
      apply: (map (fun z => propositional_extensionality z)).
      rewrite /iff cart !commute_imp; auto.
    - rewrite H/iff; auto.
  Qed.

End Later.

Notation "▷[ κ ] ϕ" := (Later.t κ ϕ) (at level 0).