(** Includes minor tweaks (mostly bug fixes?) by Brian Aydemir. *)

Create HintDb set_simpl.

(***********************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team    *)
(* <O___,, *        INRIA-Rocquencourt  &  LRI-CNRS-Orsay              *)
(*   \VV/  *************************************************************)
(*    //   *      This file is distributed under the terms of the      *)
(*         *       GNU Lesser General Public License Version 2.1       *)
(***********************************************************************)

(* $Id: FSetDecide.v 11699 2008-12-18 11:49:08Z letouzey $ *)

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

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

Require Import Decidable DecidableTypeEx FSetFacts Setoid.

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

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

    (** [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). *)
    #[global]
    Hint Constructors FSet_elt_Prop FSet_Prop : FSet_Prop.
    Ltac discard_nonFSet :=
      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].
        *)

    #[global] 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. *)
    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]. *)
    #[global]
    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 ?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].) *)
    #[global]
    Hint Resolve E.eq_refl : FSet_Auto.
    (* SCW: to change to MSets, replace with this.
    #[global]
    Hint Resolve (E.eq_equiv.(@Equivalence_Reflexive _ _)) : FSet_Auto. *)
    Ltac fsetdec_rec :=
      auto with FSet_Auto;
      subst++;
      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 with FSet_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;
    (** 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;

    (** SCW: this autorewrite can introduce [=], we need to to
        it before the next step and not just in the body. *)
    autorewrite with set_simpl in *;

    (** 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 =>
      if 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.

    Lemma test_baydemir_2 :
      forall (x : elt) (s : t),
      Subset (inter (singleton x) s) empty ->
      ~ In x s.
    Proof. fsetdec. Qed.

    Lemma test_baydemir_3 :
      forall (x y : elt) (s : t),
      ~ In x (add y s) ->
      x = y ->
      False.
    Proof. fsetdec. Qed.

    Lemma test_baydemir_4 :
      forall (x : elt) (s : t),
      Equal (inter (add x empty) s) empty ->
      ~ In x s.
    Proof. fsetdec. Qed.

    Lemma test_sweirich :
      forall (x : elt) (s : t),
        In x s -> Subset (singleton x) s.
    Proof. fsetdec. Qed.

  End FSetDecideTestCases.

End WDecide_fun.

Require Import CoqFSetInterface.

(** Now comes variants for self-contained weak seCts 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.


(*
 * Copyright 2015-2016 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *)

(** Support for defining and reasoning about sub-lists. *)

Require Import List.
Require Import ListSet.
Require Import Bool.
Require Import Permutation.
Require Import Equivalence.
Require Import Morphisms.
Require Import Setoid.
Require Import EquivDec.
Require Import RelationClasses.
Require Import Omega.
Require Import LibUtilsCoqLibAdd.
Require Import LibUtilsListAdd.
Require Import LibUtilsSortingAdd.
Require Import LibUtilsAssoc.
Require Import Program.

Section Sublist.
  (** * Sublists *)

  Section sublist.
    Context {A:Type}.
    Inductive sublist : list A -> list A -> Prop :=
    | sublist_nil : sublist nil nil
    | sublist_cons :
        forall x l1 l2, sublist l1 l2 -> sublist (x::l1) (x::l2)
    | sublist_skip :
        forall x l1 l2, sublist l1 l2 -> sublist l1 (x::l2)
    .

    Hint Constructors sublist : list.

    Lemma sublist_In {l1 l2:list A} :
      sublist l1 l2 -> forall x, In x l1 -> In x l2.
    Proof.
      induction 1; simpl; intuition.
    Qed.

    Lemma sublist_nil_l l : sublist nil l.
    Proof.
      induction l; intuition.
    Qed.

    Lemma sublist_nil_r l : sublist l nil -> l = nil.
    Proof.
      inversion 1; trivial.
    Qed.

    Global Instance sublist_incl_sub : subrelation sublist (@incl A).
    Proof.
      intros l1 l2 subl x inx.
      eapply sublist_In; eauto.
    Qed.

    Hint Immediate sublist_nil_l : list.

    Global Instance sublist_pre : PreOrder sublist.
    Proof.
      constructor; red; intros l; [induction l; intuition | ].
      intros y z; revert l y. induction z.
      - intros.
        apply sublist_nil_r in H0; subst.
        apply sublist_nil_r in H; subst.
        auto with list.
      - intros.
        inversion H0; subst; eauto 3 with list.
        inversion H; subst; eauto 3 with list.
    Qed.

    Lemma sublist_trans l1 l2 l3:
      sublist l1 l2 -> sublist l2 l3 -> sublist l1 l3.
    Proof.
      intros.
      apply (PreOrder_Transitive l1 l2 l3); assumption.
    Qed.

    Lemma sublist_length {l1 l2} : sublist l1 l2 -> length l1 <= length l2.
    Proof.
      revert l1. induction l2; simpl; intros.
      - apply sublist_nil_r in H; subst; auto.
      - inversion H; subst; simpl; auto with arith.
    Qed.

    Lemma sublist_length_eq {l1 l2} :
      sublist l1 l2 -> length l1 = length l2 -> l1 = l2.
    Proof.
      revert l1; induction l2; simpl.
      - intros; apply sublist_nil_r in H; subst; auto.
      - inversion 1; subst; simpl; intros.
        + f_equal; auto with arith.
        + apply sublist_length in H2. omega.
    Qed.

    Global Instance sublist_antisymm : Antisymmetric (list A) eq sublist.
    Proof.
      red; intros x y sub1 sub2.
      apply (sublist_length_eq sub1).
      apply sublist_length in sub1.
      apply sublist_length in sub2.
      omega.
    Qed.

    Global Instance sublist_part : PartialOrder eq sublist.
    Proof.
      unfold PartialOrder, relation_equivalence, relation_conjunction,
      predicate_equivalence, predicate_intersection, Basics.flip; simpl.
      split; intros; subst; trivial; intuition.
      apply sublist_antisymm; trivial.
    Qed.

    Global Instance sublist_NoDup : Proper (sublist --> impl) (@NoDup A).
    Proof.
      repeat red; unfold flip.
      induction x; simpl; intros.
      - apply sublist_nil_r in H; subst; auto.
      - inversion H0; subst.
        inversion H; subst; auto.
        constructor; auto.
        intro inn; apply H3.
        eapply sublist_In; eauto.
    Qed.

    Lemma sublist_app {a1 b1 a2 b2:list A}:
      sublist a1 b1 ->
      sublist a2 b2 ->
      sublist (a1 ++ a2) (b1 ++ b2).
    Proof.
      Hint Constructors sublist : list.
      revert a1 a2 b2.
      induction b1; inversion 1; subst; simpl; eauto with list.
    Qed.

    Lemma sublist_app_l (l1 l2:list A) : sublist l1 (l1 ++ l2).
    Proof.
      induction l1; simpl.
      - apply sublist_nil_l.
      - apply sublist_cons. trivial.
    Qed.

    Lemma sublist_app_r (l1 l2:list A) : sublist l2 (l1 ++ l2).
    Proof.
      induction l1; simpl.
      - reflexivity.
      - apply sublist_skip. trivial.
    Qed.

    Lemma filter_sublist f (l:list A) : sublist (filter f l) l.
    Proof.
      induction l; simpl.
      - reflexivity.
      - match_destr.
        + apply sublist_cons; trivial.
        + apply sublist_skip; trivial.
    Qed.

  End sublist.

  Hint Constructors sublist : list.

  Lemma cut_down_to_sublist
        {A B} {dec:EqDec A eq}
        (l:list (A*B)) (l2:list A) :
    sublist (cut_down_to l l2) l.
  Proof.
    unfold cut_down_to.
    apply filter_sublist.
  Qed.

  Lemma sublist_map {A B} {l1 l2} (f:A->B) :
    sublist l1 l2 -> sublist (map f l1) (map f l2).
  Proof.
    revert l1; induction l2; intros.
    - apply sublist_nil_r in H; subst; simpl; auto with list.
    - inversion H; subst; simpl; auto with list.
  Qed.

  Lemma sublist_domain {A B} {l1 l2:list(A*B)} :
    sublist l1 l2 -> sublist (domain l1) (domain l2).
  Proof.
    intros; apply sublist_map; trivial.
  Qed.

  Lemma sublist_set_inter {A} dec (l1 l2 l3:list A):
    sublist l1 l3 ->
    sublist (set_inter dec l1 l2) l3.
  Proof.
    revert l1 l2.
    induction l3; intros.
    - apply sublist_nil_r in H; subst; simpl; trivial with list.
    - inversion H; subst.
      + simpl.
        match_destr; eauto with list.
      + eauto with list.
  Qed.

  Global Instance Forall_sublist {A} {P:A->Prop} :
    Proper (sublist --> impl) (Forall P).
  Proof.
    repeat red; unfold flip.
    induction x; intros.
    - apply sublist_nil_r in H; subst; trivial.
    - inversion H0; clear H0; subst.
      inversion H; clear H; subst; auto.
  Qed.

  Lemma forallb_sublist {A} f (l1 l2:list A) :
    sublist l1 l2 ->
    forallb f l2 = true ->
    forallb f l1 = true.
  Proof.
    intros.
    eapply forallb_incl; eauto.
    apply sublist_incl_sub; trivial.
  Qed.

  Lemma forallb_ordpairs_sublist {A} f (l1 l2:list A) :
    sublist l1 l2 ->
    forallb_ordpairs f l2 = true ->
    forallb_ordpairs f l1 = true.
  Proof.
    revert l2.
    induction l1; simpl; trivial; intros.
    induction l2; simpl; inversion H; subst; simpl in * ;
      rewrite andb_true_iff in *.
    - rewrite (IHl1 l2); intuition.
      eapply forallb_sublist; eauto.
    - intuition.
  Qed.

  Lemma forallb_ordpairs_refl_sublist {A} f (l1 l2:list A) :
    sublist l1 l2 ->
    forallb_ordpairs_refl f l2 = true ->
    forallb_ordpairs_refl f l1 = true.
  Proof.
    repeat rewrite forallb_ordpairs_refl_conj.
    repeat rewrite andb_true_iff; intuition.
    - eapply forallb_ordpairs_sublist; eauto.
    - eapply forallb_sublist; eauto.
  Qed.

  Global Instance StronglySorted_sublist {A} {R:A->A->Prop} : Proper (sublist --> impl) (StronglySorted R).
  Proof.
    repeat red; unfold flip.
    induction x; simpl; intros.
    - apply sublist_nil_r in H; subst; trivial.
    - inversion H0; clear H0; subst.
      inversion H; clear H; subst; auto 3.
      rewrite <- H2 in H4; constructor; auto.
  Qed.

  Lemma is_list_sorted_sublist {A} {R} {Rdec} {l l':list A}
        `{Transitive A R} :
    @is_list_sorted A R Rdec l = true ->
    sublist l' l ->
    is_list_sorted Rdec l' = true.
  Proof.
    repeat rewrite sorted_StronglySorted by auto.
    intros ? sl.
    rewrite sl.
    trivial.
  Qed.

  Hint Immediate sublist_nil_l : list.

  Lemma StronglySorted_incl_sublist {A R l1 l2} `{EqDec A eq} `{StrictOrder A R} :
    StronglySorted R l1 ->
    StronglySorted R l2 ->
    (forall x : A, In x l1 -> In x l2) ->
    sublist l1 l2.
  Proof.
    intros.
    generalize (StronglySorted_NoDup _ H1).
    generalize (StronglySorted_NoDup _ H2).
    revert l1 H1 H2 H3.
    induction l2; simpl.
    - destruct l1; simpl; auto 1 with list.
      intros. specialize (H3 a); intuition.
    - intros. inversion H2; subst.
      destruct l1; auto 1 with list.
      simpl in *.
      inversion H1; subst.
      inversion H4; inversion H5; subst.
      destruct (a == a0); unfold Equivalence.equiv, complement in *; subst.
      unfold equiv in *.
      + apply sublist_cons. apply IHl2; trivial.
        intros x inn.
        specialize (H3 x); intuition. subst; intuition.
      + apply sublist_skip. apply IHl2; auto.
        simpl; intros x inn.
        generalize (H3 a0).
        specialize (H3 _ inn). intuition; subst.
        * intuition.
        * rewrite Forall_forall in H9,H11.
          specialize (H11 _ H3).
          specialize (H9 _ H14).
          rewrite H9 in H11.
          eelim irreflexivity; eauto.
  Qed.

  Lemma Sorted_incl_sublist {A R l1 l2} `{EqDec A eq} `{StrictOrder A R}:
    Sorted R l1 ->
    Sorted R l2 ->
    (forall x : A, In x l1 -> In x l2) ->
    sublist l1 l2.
  Proof.
    intros.
    apply StronglySorted_incl_sublist; trivial;
      apply Sorted_StronglySorted; trivial; apply StrictOrder_Transitive.
  Qed.

  Lemma Sorted_incl_both_eq {A R l1 l2} `{EqDec A eq} `{StrictOrder A R}:
    Sorted R l1 ->
    Sorted R l2 ->
    (forall x : A, In x l1 -> In x l2) ->
    (forall x : A, In x l2 -> In x l1) ->
    l1 = l2.
  Proof.
    intros.
    apply sublist_antisymm; apply Sorted_incl_sublist; trivial.
  Qed.

  Lemma insertion_sort_equivlist_strong {A R R_dec} `{EqDec A eq} `{StrictOrder A R} l l' (contr:asymmetric_over R l) :
    equivlist l l' ->
    @insertion_sort A R R_dec l =
    @insertion_sort A R R_dec l'.
  Proof.
    intros.
    generalize (equivlist_insertion_sort_strong R_dec contr H1); intros.
    apply Sorted_incl_both_eq; try apply insertion_sort_Sorted.
    intros. eapply equivlist_in; eauto.
    intros. symmetry in H2. eapply equivlist_in; eauto.
  Qed.

  Lemma insertion_sort_equivlist {A R R_dec} `{EqDec A eq} `{StrictOrder A R}  (contr:forall x y,  ~R x y -> ~R y x -> x = y) l l' :
    equivlist l l' ->
    @insertion_sort A R R_dec l =
    @insertion_sort A R R_dec l'.
  Proof.
    intros.
    apply insertion_sort_equivlist_strong; eauto.
    eapply asymmetric_asymmetric_over; trivial.
  Qed.

  Lemma sublist_skip_l {A} (a:A) {l1 l2} :
    sublist (a::l1) l2 ->
    sublist l1 l2.
  Proof.
    revert l1.
    induction l2; inversion 1; subst.
    - apply sublist_skip; trivial.
    - apply sublist_skip. eauto.
  Qed.

  Lemma sublist_cons_eq_inv {A a l1 l2} :
    @sublist A (a::l1) (a::l2) ->
    sublist l1 l2.
  Proof.
    inversion 1; subst; trivial.
    rewrite <- H2. apply sublist_skip; reflexivity.
  Qed.

  Lemma sublist_filter {A} (f:A->bool) {l1 l2} :
    sublist l1 l2 -> sublist (filter f l1) (filter f l2).
  Proof.
    revert l1. induction l2; simpl; intros.
    - apply sublist_nil_r in H; subst; simpl; auto 1 with list.
    - inversion H; subst.
      + specialize (IHl2 _ H2); simpl.
        destruct (f a); [apply sublist_cons | ]; congruence.
      + specialize (IHl2 _ H2); simpl.
        destruct (f a); [apply sublist_skip | ]; congruence.
  Qed.

  Lemma sublist_cons_inv' {A B l1 a l2} :
    sublist l1(a::l2) ->
    NoDup (@domain A B (a::l2)) ->
    (exists l',
        l1 = a::l' /\ sublist l' l2)
    \/
    (~ In (fst a) (domain l1)
     /\ sublist l1 l2).
  Proof.
    inversion 1; subst.
    intuition; eauto.
    intros; right. split; trivial.
    generalize (sublist_In (sublist_domain H2)); intros inn.
    inversion H0; subst.
    auto.
  Qed.

  Lemma sublist_cons_inv {A B l1 a l2 R R_dec} `{StrictOrder A R}:
    sublist l1(a::l2) ->
    @is_list_sorted A R R_dec (@domain _ B (a::l2)) = true ->
    (exists l',
        l1 = a::l' /\ sublist l' l2)
    \/
    (~ In (fst a) (domain l1)
     /\ sublist l1 l2).
  Proof.
    inversion 1; subst.
    intuition; eauto.
    intros; right. split; trivial.
    generalize (sublist_In (sublist_domain H3)); intros inn.
    apply is_list_sorted_NoDup in H1; eauto.
    inversion H1; subst.
    auto.
  Qed.

  Lemma sublist_cons_inv_simple {A l1} {a:A} {l2} :
    sublist l1(a::l2) ->
    NoDup (a::l2) ->
    (exists l',
        l1 = a::l' /\ sublist l' l2)
    \/
    (~ In a l1
     /\ sublist l1 l2).
  Proof.
    inversion 1; subst.
    intuition; eauto.
    intros; right. split; trivial.
    generalize (sublist_In H2); intros inn.
    inversion H0; subst.
    auto.
  Qed.

  Lemma sublist_dec {A}  {dec:EqDec A eq} (l1 l2 : list A) :
    {sublist l1 l2} + { ~ sublist l1 l2}.
  Proof.
    revert l1.
    induction l2; intros l1; destruct l1.
    - left; trivial with list.
    - right; inversion 1.
    - left; apply sublist_nil_l.
    - destruct (a0 == a).
      + destruct (IHl2 l1).
        * left. rewrite e. eauto with list.
        * right. rewrite e. intro subl.
          apply sublist_cons_eq_inv in subl.
          intuition.
      + destruct (IHl2 (a0::l1)).
        * left. apply sublist_skip; trivial.
        * right; inversion 1; subst; intuition.
  Defined.

  Lemma sublist_remove {A} dec (x:A) l1 l2 :
    sublist l1 l2 ->
    sublist (remove dec x l1) (remove dec x l2).
  Proof.
    revert l1. induction l2; simpl; intros.
    - apply sublist_nil_r in H; subst; simpl; auto 1 with list.
    - inversion H; subst.
      + specialize (IHl2 _ H2); simpl.
        match_destr. apply sublist_cons; auto.
      + specialize (IHl2 _ H2); simpl.
        match_destr.
        apply sublist_skip; auto.
  Qed.

  Lemma sublist_nin_remove {A} dec (l1 l2:list (A)) a :
    ~ In a l1 -> sublist l1 l2 -> sublist l1 (remove dec a l2).
  Proof.
    intros.
    apply (sublist_remove dec a) in H0.
    rewrite (nin_remove dec l1 a) in H0 by trivial.
    trivial.
  Qed.

  Lemma assoc_lookupr_nodup_sublist {A B} {R_dec:forall a a' : A, {a = a'} + {a <> a'}} {l1 l2} {a:A} {b:B} :
    NoDup (domain l2) ->
    sublist l1 l2 ->
    assoc_lookupr R_dec l1 a = Some b ->
    assoc_lookupr R_dec l2 a = Some b.
  Proof.
    revert a b l1.  induction l2; simpl; intros.
    - apply sublist_nil_r in H0; subst. simpl in *; discriminate.
    - destruct a; simpl.
      generalize (sublist_cons_inv' H0 H).
      inversion H; subst.
      destruct 1.
      + destruct H2 as [? [??]]; subst.
        simpl in H1.
        case_eq (assoc_lookupr R_dec x a0); [ intros? eqq | intros eqq]
        ; rewrite eqq in H1.
        * inversion H1; clear H1; subst.
          rewrite (IHl2 _ _ _ H5 H3 eqq); trivial.
        * destruct (R_dec a0 a); inversion H1; subst.
          case_eq (assoc_lookupr R_dec l2 a); trivial.
          intros.
          apply assoc_lookupr_in in H2.
          apply in_dom in H2.
          congruence.
      + simpl in H2. destruct H2.
        rewrite (IHl2 _ _ _ H5 H3 H1); trivial.
  Qed.

  Lemma insertion_sort_insert_sublist_self {A R}
        R_dec (a:A) l :
    sublist l (@insertion_sort_insert A R R_dec a l).
  Proof.
    induction l; simpl.
    - apply sublist_skip; reflexivity.
    - match_destr.
      + apply sublist_skip; apply sublist_cons; reflexivity.
      + match_destr; try reflexivity.
        apply sublist_cons.
        eauto.
  Qed.

  Lemma insertion_sort_insert_sublist_prop {A R} {rstrict:StrictOrder R}
        (trich:forall a b, {R a b} + {a = b} + {R b a})
        R_dec a l1 l2:
    is_list_sorted R_dec l2 = true ->
    sublist l1 l2 ->
    sublist (@insertion_sort_insert A R R_dec a l1)
            (@insertion_sort_insert A R R_dec a l2).
  Proof.
    unfold Proper, respectful; intros; subst.
    revert l1 H H0. induction l2.
    - inversion 2; subst; simpl; reflexivity.
    - intros. apply sublist_cons_inv_simple in H0;
                [ | apply (is_list_sorted_NoDup R_dec); trivial].
      destruct H0 as [[?[??]]|[??]]; subst.
      + simpl. match_destr.
        * do 2 apply sublist_cons; eauto.
        * match_destr; apply sublist_cons; trivial.
          apply IHl2; trivial.
          eapply is_list_sorted_cons_inv; eauto.
      + simpl. match_destr.
        * rewrite IHl2; trivial; [| eapply is_list_sorted_cons_inv; eauto].
          rewrite insertion_sort_insert_forall_lt.
          { apply sublist_cons; apply sublist_skip; reflexivity. }
          apply sorted_StronglySorted in H; [| eapply StrictOrder_Transitive].
          inversion H; subst.
          revert H5. apply Forall_impl; intros.
          rewrite <- H2; trivial.
        * specialize (IHl2 l1).
          cut_to IHl2; trivial; [| eapply is_list_sorted_cons_inv; eauto].
          match_destr; [apply sublist_skip; trivial | ].
          destruct (trich a a0) as [[?|?]|?]; try congruence.
          subst.
          rewrite insertion_sort_insert_forall_lt; [ apply sublist_cons; trivial | ].
          rewrite H1.
          apply sorted_StronglySorted in H; [| eapply StrictOrder_Transitive].
          inversion H; subst. trivial.
  Qed.

  Lemma insertion_sort_sublist_proper {A R} {rstrict:StrictOrder R}
        (trich:forall a b, {R a b} + {a = b} + {R b a}) R_dec :
    Proper (sublist ==> sublist) (@insertion_sort A R R_dec).
  Proof.
    unfold Proper, respectful; intros.
    revert x H. induction y; simpl; inversion 1; subst; simpl; trivial.
    - specialize (IHy _ H2).
      apply insertion_sort_insert_sublist_prop; trivial.
      apply is_list_sorted_Sorted_iff.
      apply insertion_sort_Sorted.
    - rewrite IHy; trivial.
      apply insertion_sort_insert_sublist_self.
  Qed.

  Lemma sublist_of_sorted_sublist {A R} {rstrict:StrictOrder R}
        (trich:forall a b, {R a b} + {a = b} + {R b a})
        R_dec {l1 l2} :
    sublist (@insertion_sort A R R_dec l1) l2 ->
    forall l1',
      sublist l1' l1 ->
      sublist (insertion_sort R_dec l1') l2.
  Proof.
    intros.
    transitivity (insertion_sort R_dec l1); trivial.
    apply insertion_sort_sublist_proper; trivial.
  Qed.

  Lemma incl_NoDup_sublist_perm {A} {dec:EqDec A eq} {l1 l2:list A} :
    NoDup l1 ->
    incl l1 l2 ->
    exists l1', Permutation l1 l1' /\ sublist l1' l2.
  Proof.
    unfold incl.
    revert l1.
    induction l2; simpl.
    - destruct l1; simpl; eauto 3 with list.
      intros ? inn.
      specialize (inn a); intuition.
    - intros.
      case_eq (In_dec dec a l1); intros.
      + destruct (in_split _ _ i) as [x [y ?]]; subst.
        assert (perm:Permutation (x ++ a :: y) (a::x ++ y))
          by (rewrite Permutation_middle; reflexivity).
        rewrite perm in H.
        inversion H; clear H; subst.
        destruct (IHl2 (x++y)) as [l1' [l1'perm l1'incl]]; trivial.
        * intros ? inn.
          { destruct (H0 a0); trivial.
            - rewrite perm; simpl; intuition.
            - subst. intuition.
          }
        * exists (a::l1').
          { split.
            - rewrite perm.
              eauto.
            - apply sublist_cons.
              trivial.
          }
      + destruct (IHl2 l1 H) as [x [perm subl]].
        * intros ? inn.
          destruct (H0 _ inn); subst; intuition.
        * exists x; split; trivial.
          apply sublist_skip.
          trivial.
  Qed.

  Lemma incl_NoDup_length_le {A} {dec:EqDec A eq} {l1 l2:list A} :
    NoDup l1 ->
    incl l1 l2 ->
    length l1 <= length l2.
  Proof.
    intros nd inc.
    destruct (incl_NoDup_sublist_perm nd inc) as [l1' [perm subl]].
    rewrite (Permutation_length perm).
    apply sublist_length.
    trivial.
  Qed.

  Lemma find_fresh_from {A} {dec:EqDec A eq} (bad l:list A) :
    length l > length bad ->
    NoDup l ->
    {y | find (fun x : A => if in_dec equiv_dec x bad then false else true) l = Some y}.
  Proof.
    rewrite find_filter.
    unfold hd_error.
    match_case; eauto; intros.
    generalize (filter_nil_implies_not_pred _ l H); intros.
    cut (length l <= length bad); [intuition|].
    apply incl_NoDup_length_le; trivial.
    intros ? inn.
    specialize (H2 _ inn).
    match_destr_in H2.
  Defined.

  Lemma concat_sublist {A} (ls:list (list A)) :
    Forall (fun x : list A => sublist x (concat ls)) ls.
  Proof.
    induction ls; simpl; trivial.
    constructor.
    - apply sublist_app_l.
    - revert IHls.
      apply Forall_impl; intros ? subl.
      rewrite subl.
      apply sublist_app_r.
  Qed.

  Lemma sublist_perm_head {A:Type} {l1 l2 : list A} :
    sublist l1 l2 ->
    exists t,
      Permutation (l1++t) l2.
  Proof.
    intros subl; induction subl.
    - exists nil; simpl; reflexivity.
    - destruct IHsubl as [t perm].
      simpl.
      exists t.
      rewrite <- perm.
      reflexivity.
    - destruct IHsubl as [t perm].
      exists (x::t).
      rewrite <- perm.
      rewrite <- Permutation_cons_app; reflexivity.
  Qed.

  Lemma Permutation_sublist_pullback_r {A:Type} {l1 l1' l2:list A} :
    sublist l1 l1' ->
    Permutation l1 l2 ->
    exists l2',
      Permutation l1' l2' /\
      sublist l2 l2'.
  Proof.
    intros subl perm.
    revert l1' subl.
    revert l1 l2 perm.
    change (forall l1 l2 : list A,
               Permutation l1 l2 ->
               (fun l1 l2 => forall l1' : list A, sublist l1 l1' -> exists l2' : list A, Permutation l1' l2' /\ sublist l2 l2') l1 l2).
    apply Permutation_ind_bis; simpl; intros.
    - exists l1'; split; trivial.
    - dependent induction H1.
      + destruct (H0 _ H1) as [ll [perm subl]].
        exists (x::ll).
        split.
        * eauto.
        * constructor; trivial.
      + destruct (IHsublist x l l' H H0 (eq_refl _)) as [ll [perm subl]].
        exists (x0::ll).
        split.
        * eauto.
        * constructor; trivial.
    - revert l' H H0 H1.
      induction l1'; intros l' perm IH subl.
      + invcs subl.
      + specialize (IHl1' _ perm IH).
        invcs subl.
        * clear IHl1'.
          { revert l' H0 perm IH.
            induction l1'; intros l' subl perm1 IH1.
            - invcs subl.
            - invcs subl.
              + destruct (IH1 _ H0) as [ll [perm2 subl2]].
                exists (a0::a::ll); split.
                * rewrite perm_swap, perm2; trivial.
                * do 2 constructor; trivial.
              + destruct (IHl1' _ H1 perm1 IH1) as [ll [perm2 subl2]].
                exists (a0::ll); split.
                * rewrite <- perm2, perm_swap; trivial.
                * constructor; trivial.
          }
        * destruct (IHl1' H1) as [ll [perm2 subl2]].
          exists (a::ll).
          { split.
            - constructor; trivial.
            - constructor; trivial.
          }
    - destruct (H0 _ H3) as [ll [perm1 subl1]].
      destruct (H2 _ subl1) as [ll' [perm2 subl2]].
      exists ll'.
      split; trivial.
      rewrite <- perm2; trivial.
  Qed.

  Lemma Permutation_filter_pullback_r {A:Type} {f:A->bool} {l1 l2} :
    Permutation (filter f l1) l2 ->
    exists l2',
      l2 = filter f l2' /\ Permutation l1 l2'.
  Proof.
    cut (forall l1 l2 : list A,
            Permutation l1 l2 ->
            (fun l1 l2 => forall l1', l1 = filter f l1' ->
                                      exists l2',
                                        l2 = filter f l2' /\ Permutation l1' l2') l1 l2).
    { intros H; intros.
      specialize (H _ _ H0); simpl in H.
      specialize (H _ (eq_refl _)).
      eauto.
    }
    apply Permutation_ind_bis; simpl; intros.
    - exists l1'; split; trivial.
    - induction l1'; simpl in *; try discriminate.
      match_case_in H1; intros eqq; rewrite eqq in H1.
      + invcs H1.
        destruct (H0 _ (eq_refl _))
          as [ll [? perm]]; subst.
        exists (a::ll); split; simpl.
        * rewrite eqq; trivial.
        * constructor; trivial.
      + destruct (IHl1' H1)
          as [ll [? perm]]; subst.
        exists (a::ll); split; simpl.
        * rewrite eqq; trivial.
        * constructor; trivial.
    - induction l1'; simpl in *; try discriminate.
      match_case_in H1; intros eqq1; rewrite eqq1 in H1.
      + invcs H1.
        clear IHl1'.
        revert l H H0 H4.
        induction l1'; simpl in *; try discriminate; intros.
        { match_case_in H4; intros eqq2; rewrite eqq2 in *.
          + invcs H4.
            destruct (H0 _ (eq_refl _))
              as [ll [? perm]]; subst.
            exists (a0::a::ll); split; simpl.
            * rewrite eqq1, eqq2; trivial.
            * rewrite perm_swap, perm; trivial.
          + destruct (IHl1' _ H H0 H4)
              as [ll [? perm]]; subst.
            exists (a0::ll); split; simpl.
            * rewrite eqq2; trivial.
            * rewrite perm_swap, perm; trivial.
        }
      + { destruct (IHl1' H1)
            as [ll [? perm]]; subst.
          exists (a::ll); split.
          + simpl; rewrite eqq1; trivial.
          + constructor; trivial.
        }
    - subst.
      destruct (H0 _ (eq_refl _))
        as [ll [? perm]]; subst.
      destruct (H2 _ (eq_refl _))
        as [ll2 [? perm2]]; subst.
      exists ll2; split; trivial.
      rewrite perm; trivial.
  Qed.

  Lemma filter_perm_head {A:Type} {f:A->bool} {l1 l2} :
    Permutation (filter f l1) l2 ->
    exists t,
      Permutation l1 (l2++t).
  Proof.
    intros.
    generalize (filter_sublist f l1); intros subl.
    destruct (sublist_perm_head subl)
      as [x perm].
    rewrite H in perm.
    symmetry in perm.
    eauto.
  Qed.

  Lemma Permutation_filter {A : Type} (f : A -> bool) (l l' : list A) :
    Permutation l l' -> Permutation (filter f l) (filter f l').
  Proof.
    revert l l'.
    apply Permutation_ind_bis; simpl; intros.
    - trivial.
    - match_case; eauto.
    - repeat match_case; eauto 2; intros.
      rewrite perm_swap; eauto.
    - rewrite H0, H2; trivial.
  Qed.

End Sublist.
Hint Immediate sublist_nil_l : list.