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

(** * MSetFullAVL : some complements to MSetAVL

   - Functor [AvlProofs] proves that trees of [MSetAVL] are not only
   binary search trees, but moreover well-balanced ones. This is done
   by proving that the operations in [MSetAVL.Ops] preserve the balancing.

   - We propose two functors [IntMake] and [Make] similar to the ones
   of [MSetAVL], except that the two invariants (bst and avl)
   are maintained instead of only the first one.

   - Functor [OcamlOps] contains variants of [union], [subset],
   [compare] and [equal] that are faithful to the original ocaml codes,
   while the versions in MSetAVL have been adapted to perform only
   structural recursive code.
*)

Require Import ZArith Int ROmega MSetInterface MSetAVL NPeano.
Require Import FunInd.

Module AvlProofs (Import I:Int)(X:OrderedType).
Include MSetAVL.MakeRaw I X.
Module Import II := MoreInt I.
Local Open Scope pair_scope.
Local Open Scope Int_scope.

Ltac omega_max := i2z_refl; romega with Z.
Ltac mysubst :=
 match goal with
   | E : _=_ |- _ => rewrite E in *; clear E; mysubst
   | _ => idtac
 end.

(** * AVL trees *)

(** [avl s] : [s] is a properly balanced AVL tree,
    i.e. for any node the heights of the two children
    differ by at most 2 *)

Inductive avl : tree -> Prop :=
  | RBLeaf : avl Leaf
  | RBNode : forall x l r h, avl l -> avl r ->
      -(2) <= height l - height r <= 2 ->
      h = max (height l) (height r) + 1 ->
      avl (Node h l x r).

Class Avl (t:tree) : Prop := mkAvl : avl t.

Instance avl_Avl s (Hs : avl s) : Avl s := Hs.

(** * Automation and dedicated tactics *)

Local Hint Constructors avl.

(** A tactic for cleaning hypothesis after use of functional induction. *)

Ltac clearf :=
 match goal with
  | H : (@Logic.eq (sumbool _ _) _ _) |- _ => clear H; clearf
  | H : (_ =? _) = true |- _ => rewrite II.eqb_eq in H; clearf
  | H : (_ <? _) = true |- _ => rewrite II.ltb_lt in H; clearf
  | H : (_ <=? _) = true |- _ => rewrite II.leb_le in H; clearf
  | H : (_ =? _) = false |- _ => rewrite II.eqb_neq in H; clearf
  | H : (_ <? _) = false |- _ => rewrite II.ltb_nlt in H; clearf
  | H : (_ <=? _) = false |- _ => rewrite II.leb_nle in H; clearf
  | _ => idtac
 end.

Ltac avl2Avl := change avl with Avl in *.
Ltac Avl2avl := change Avl with avl in *.
Ltac inv_avl := Avl2avl; invtree avl; avl2Avl.
(* Similar, but non-recursive *)
Ltac inv_avl' :=
  match goal with H : Avl (Node _ _ _ _) |- _ =>
    inversion_clear H; avl2Avl
  end.

(** Tactics about [avl] *)

Lemma height_non_negative : forall s `{Avl s}, height s >= 0.
Proof.
 induction s; simpl; intros; auto with zarith.
 inv_avl; intuition; omega_max.
Qed.

(** When [H:Avl r], typing [avl_nn H] adds [height r >= 0] *)

Ltac avl_nn H :=
  let nz := fresh "nz" in assert (nz := @height_non_negative _ H).

(* Repeat the previous tactic, clearing the [Avl _] hyps *)

Ltac avl_nns :=
  match goal with
     | H:Avl _ |- _ => avl_nn H; clear H; avl_nns
     | _ => idtac
  end.

(** Results about [height] *)

Lemma height_0 : forall s `{Avl s}, height s = 0 -> s = Leaf.
Proof.
 destruct 1; avl2Avl; intuition; simpl in *.
 avl_nns. simpl in *; exfalso; omega_max.
Qed.

(** Results about [avl] *)

Lemma avl_node :
 forall x l r `{Avl l, Avl r},
 -(2) <= height l - height r <= 2 ->
 Avl (Node (max (height l) (height r) + 1) l x r).
Proof.
  auto_tc.
Qed.
Hint Resolve avl_node.

(** * AVL trees have indeed logarithmic depth *)

Module LogDepth.

Local Open Scope nat_scope.

(** The minimal cardinal of an AVL tree of a given height.
    NB: this minimal cardinal is optimal, i.e. for any height,
    we could build an AVL tree of this cardinal. *)

Fixpoint mincard n :=
 match n with
 | O => O
 | 1 => 1
 | 2 => 2
 | S (S (S n) as p) => S (mincard n + mincard p)
 end.

(** First, some basic properties of [mincard] *)

Lemma mincard_eqn n :
 mincard (S (S (S n))) = S (mincard n + mincard (2+n)).
Proof.
 reflexivity.
Qed.

Lemma mincard_incr n : mincard n < mincard (S n).
Proof.
 induction n using lt_wf_ind.
 do 3 (destruct n; auto).
 rewrite 2 mincard_eqn.
 apply -> Nat.succ_lt_mono.
 apply Nat.add_lt_mono; eauto.
Qed.

Lemma mincard_lt_mono n m : n < m -> mincard n < mincard m.
Proof.
 induction m; inversion_clear 1.
 - apply mincard_incr.
 - transitivity (mincard m); auto using mincard_incr.
Qed.

Lemma mincard_le_mono n m : n <= m -> mincard n <= mincard m.
Proof.
 induction 1; auto.
 transitivity (mincard m); auto using mincard_incr with arith.
Qed.

Lemma mincard_bound n m : m <= 2+n ->
 mincard (S m) <= S (mincard n + mincard m).
Proof.
 intros H.
 destruct m as [|[|m]].
 - simpl. auto with arith.
 - simpl. auto with arith.
 - rewrite mincard_eqn.
   apply -> Nat.succ_le_mono.
   apply Nat.add_le_mono; eauto.
   apply mincard_le_mono; omega.
Qed.

(** [mincard] has an exponential behavior *)

Lemma mincard_twice n : 2 * mincard n < mincard (2+n).
Proof.
 induction n as [n IH] using lt_wf_ind.
 do 3 (destruct n; [simpl; auto with arith|]).
 change (2 + S (S (S n))) with (S (S (S (2+n)))).
 rewrite 2 mincard_eqn.
 generalize (IH n) (IH (2+n)). omega.
Qed.

Lemma mincard_even n : n<>0 -> 2^n <= mincard (2*n).
Proof.
 induction n.
 - now destruct 1.
 - intros _.
   destruct (Nat.eq_dec n 0).
   * subst; simpl; auto.
   * rewrite Nat.pow_succ_r', Nat.mul_succ_r, Nat.add_comm.
     transitivity (2 * mincard (2*n)).
     + apply Nat.mul_le_mono_l; auto.
     + apply Nat.lt_le_incl. apply mincard_twice.
Qed.

Lemma mincard_odd n : 2^n <= mincard (2*n+1).
Proof.
 destruct (Nat.eq_dec n 0).
 - subst; auto.
 - transitivity (mincard (2*n)).
   * now apply mincard_even.
   * apply mincard_le_mono. omega.
Qed.

Lemma mincard_log n : n <= 2 * Nat.log2 (mincard n) + 1.
Proof.
 rewrite (Nat.div2_odd n).
 set (m := Nat.div2 n); clearbody m.
 destruct (Nat.odd n); simpl Nat.b2n; rewrite ?Nat.add_0_r; clear n.
 + apply Nat.add_le_mono_r, Nat.mul_le_mono_l.
   apply Nat.log2_le_pow2.
   apply (mincard_lt_mono 0); auto with arith.
   apply mincard_odd.
 + destruct (Nat.eq_dec m 0); [subst; simpl; auto|].
   transitivity (2*Nat.log2 (mincard (2*m))); [|omega].
   apply Nat.mul_le_mono_l.
   apply Nat.log2_le_pow2.
   apply (mincard_lt_mono 0); omega.
   now apply mincard_even.
Qed.

(** We now prove that [mincard] gives indeed a lower bound
    of the cardinal of AVL trees. *)

Lemma maxdepth_heigth s : Avl s ->
 Z.of_nat (maxdepth s) = i2z (height s).
Proof.
 induction 1.
 simpl. omega_max.
 simpl maxdepth. simpl height. subst h.
 rewrite Nat2Z.inj_succ, Nat2Z.inj_max. omega_max.
Qed.

Lemma mincard_maxdepth s :
 Avl s -> mincard (maxdepth s) <= cardinal s.
Proof.
 induction 1.
 - simpl; auto.
 - simpl maxdepth. simpl cardinal. subst h.
   destruct (Nat.max_spec (maxdepth l) (maxdepth r)) as [(U,->)|(U,->)].
   * rewrite mincard_bound.
     apply -> Nat.succ_le_mono.
     apply Nat.add_le_mono; eauto.
     apply Nat2Z.inj_le. rewrite Nat2Z.inj_add.
     rewrite 2 maxdepth_heigth by auto. simpl Z.of_nat.
     i2z. omega.
   * rewrite Nat.add_comm, mincard_bound.
     apply -> Nat.succ_le_mono.
     apply Nat.add_le_mono; eauto.
     apply Nat2Z.inj_le. rewrite Nat2Z.inj_add.
     rewrite 2 maxdepth_heigth by auto. simpl Z.of_nat.
     i2z. omega.
Qed.

(** We can now prove that the depth of an AVL tree is
    logarithmic in its size. *)

Lemma maxdepth_upperbound s : Avl s ->
 maxdepth s <= 2 * Nat.log2 (cardinal s) + 1.
Proof.
 intros.
 transitivity (2 * Nat.log2 (mincard (maxdepth s)) + 1).
 apply mincard_log.
 apply Nat.add_le_mono_r, Nat.mul_le_mono_l, Nat.log2_le_mono.
 now apply mincard_maxdepth.
Qed.

Lemma maxdepth_lowerbound s : s<>Leaf ->
 Nat.log2 (cardinal s) < maxdepth s.
Proof.
 apply maxdepth_log_cardinal.
Qed.

End LogDepth.

(** * The AVL invariant is preserved by set operations *)

(** empty *)

Instance empty_avl : Avl empty.
Proof.
 auto_tc.
Qed.

(** singleton *)

Instance singleton_avl (x:elt) : Avl (singleton x).
Proof.
 unfold singleton. constructor; auto; simpl; omega_max.
Qed.

(** create *)

Lemma create_avl :
 forall l x r `{Avl l, Avl r},
   -(2) <= height l - height r <= 2 ->
   Avl (create l x r).
Proof.
 unfold create; auto.
Qed.

Lemma create_height :
 forall l x r `{Avl l, Avl r},
   -(2) <= height l - height r <= 2 ->
   height (create l x r) = max (height l) (height r) + 1.
Proof.
 unfold create; auto.
Qed.

(** bal *)

Ltac when f :=
 match goal with |- context [f] => idtac | _ => fail end.

Lemma bal_avl :
  forall l x r `{Avl l, Avl r},
    -(3) <= height l - height r <= 3 ->
    Avl (bal l x r).
Proof.
 intros l x r; functional induction bal l x r; intros; clearf;
 inv_avl; simpl in *; try (when assert_false; avl_nns);
 repeat apply create_avl; simpl in *; auto; omega_max.
Qed.

Lemma bal_height_1 :
  forall l x r `{Avl l, Avl r},
    -(3) <= height l - height r <= 3 ->
    0 <= height (bal l x r) - max (height l) (height r) <= 1.
Proof.
 intros l x r; functional induction bal l x r; intros; clearf;
 inv_avl; avl_nns; simpl in *; omega_max.
Qed.

Lemma bal_height_2 :
 forall l x r `{Avl l, Avl r},
   -(2) <= height l - height r <= 2 ->
   height (bal l x r) == max (height l) (height r) +1.
Proof.
 intros l x r; functional induction bal l x r; intros; clearf;
 inv_avl; simpl in *; omega_max.
Qed.

Ltac omega_bal := match goal with
  | _:Avl ?l, _:Avl ?r |- context [ bal ?l ?x ?r ] =>
     generalize (bal_height_1 l x r) (bal_height_2 l x r);
     omega_max
  end.

(** add *)

Lemma add_avl_1 : forall s x `{Avl s},
 Avl (add x s) /\ 0 <= height (add x s) - height s <= 1.
Proof.
 induct s x; inv_avl.
 - intuition; try constructor; simpl; auto; omega_max.
 - (* Eq *)
   simpl. intuition; omega_max.
 - (* Lt *)
   destruct (IHl x); trivial.
   split.
   * apply bal_avl; trivial; omega_max.
   * omega_bal.
 - (* Gt *)
   destruct (IHr x); trivial.
   split.
   * apply bal_avl; trivial; omega_max.
   * omega_bal.
Qed.

Instance add_avl s x `{Avl s} : Avl (add x s).
Proof.
 now destruct (add_avl_1 s x).
Qed.

(** join *)

Ltac remtree t s :=
 match t with Node ?h _ _ _ =>
  assert (height t = h) by trivial;
  set (s := t) in *; clearbody s
 end.

Lemma join_avl_1 : forall l x r `{Avl l, Avl r},
 Avl (join l x r) /\
 0<= height (join l x r) - max (height l) (height r) <= 1.
Proof.
 join_tac; clearf.

 - simpl. destruct (add_avl_1 r x). split; trivial.
   avl_nns; omega_max.

 - remtree (Node lh ll lx lr) l.
   split; auto_tc.
   destruct (add_avl_1 l x).
   simpl. avl_nns; omega_max.

 - remtree (Node rh rl rx rr) r.
   inv_avl.
   destruct (Hlr x r); trivial; clear Hrl Hlr.
   set (j := join lr x r) in *; clearbody j.
   simpl.
   assert (-(3) <= height ll - height j <= 3) by omega_max.
   split.
   * apply bal_avl; trivial.
   * omega_bal.

 - remtree (Node lh ll lx lr) l.
   inv_avl.
   destruct Hrl; trivial; clear Hlr.
   set (j := join l x rl) in *; clearbody j.
   simpl.
   assert (-(3) <= height j - height rr <= 3) by omega_max.
   split.
   * apply bal_avl; trivial.
   * omega_bal.

 - clear Hrl Hlr.
   remtree (Node lh ll lx lr) l.
   remtree (Node rh rl rx rr) r.
   assert (-(2) <= height l - height r <= 2) by omega_max.
   split.
   * apply create_avl; trivial.
   * rewrite create_height; trivial; omega_max.
Qed.

Instance join_avl l x r `{Avl l, Avl r} : Avl (join l x r).
Proof.
 now destruct (join_avl_1 l x r).
Qed.

(** remove_min *)

Lemma remove_min_avl_1 : forall l x r h `{Avl (Node h l x r)},
 Avl (remove_min l x r)#1 /\
 0 <= height (Node h l x r) - height (remove_min l x r)#1 <= 1.
Proof.
 intros l x r; functional induction (remove_min l x r);
 subst; simpl in *; intros.
 - inv_avl; simpl in *; split; auto. avl_nns; omega_max.
 - mysubst. inv_avl'; simpl in *.
   edestruct IHp; clear IHp; [eauto|].
   split.
   * apply bal_avl; trivial; omega_max.
   * omega_bal.
Qed.

Instance remove_min_avl l x r h `{Avl (Node h l x r)} :
  Avl (remove_min l x r)#1.
Proof.
 now destruct (remove_min_avl_1 l x r h).
Qed.

(** merge *)

Lemma merge_avl_1 : forall s1 s2 `{Avl s1, Avl s2},
 -(2) <= height s1 - height s2 <= 2 ->
 Avl (merge s1 s2) /\
 0<= height (merge s1 s2) - max (height s1) (height s2) <=1.
Proof.
 intros s1 s2; functional induction (merge s1 s2); intros;
 try (factornode s1).
 - simpl; split; auto; avl_nns; omega_max.
 - simpl; split; auto; avl_nns; simpl in *; omega_max.
 - generalize (@remove_min_avl_1 l2 x2 r2 _ _).
   mysubst. destruct 1; simpl in *.
   split.
   * apply bal_avl; trivial. simpl; omega_max.
   * omega_bal.
Qed.

Lemma merge_avl s1 s2 `{Avl s1, Avl s2} :
  -(2) <= height s1 - height s2 <= 2 -> Avl (merge s1 s2).
Proof.
 intros; now destruct (merge_avl_1 s1 s2).
Qed.

(** remove *)

Lemma remove_avl_1 : forall s x `{Avl s},
 Avl (remove x s) /\ 0 <= height s - height (remove x s) <= 1.
Proof.
 induct s x; inv_avl.
 - intuition; omega_max.
 - (* Eq *)
   generalize (merge_avl_1 l r).
   intuition omega_max.
 - (* Lt *)
   destruct (IHl x); trivial.
   split.
   * apply bal_avl; trivial; omega_max.
   * omega_bal.
 - (* Gt *)
   destruct (IHr x); trivial.
   split.
   * apply bal_avl; trivial; omega_max.
   * omega_bal.
Qed.

Instance remove_avl s x `{Avl s} : Avl (remove x s).
Proof.
 now destruct (remove_avl_1 s x).
Qed.

(** concat *)

Instance concat_avl s1 s2 `{Avl s1, Avl s2} : Avl (concat s1 s2).
Proof.
 functional induction (concat s1 s2); auto.
 apply join_avl; auto.
 generalize (remove_min_avl l2 x2 r2 _). now mysubst.
Qed.

(** split *)

Functional Scheme split_ind := Induction for split Sort Prop.

Lemma split_avl : forall s x `{Avl s},
  Avl (split x s)#l /\ Avl (split x s)#r.
Proof.
 intros s x. functional induction (split x s); simpl; auto.
 - intros. inv_avl; auto.
 - mysubst; simpl in *; inversion_clear 1; intuition.
 - mysubst; simpl in *; inversion_clear 1; intuition.
Qed.

(** inter *)

Ltac split_tac x1 :=
 let s2 := fresh "s2" in
 auto; factornode s2; generalize (split_avl s2 x1);
 mysubst; simpl; destruct 1; inv_avl; auto_tc.

Instance inter_avl s1 s2 `{Avl s1, Avl s2} : Avl (inter s1 s2).
Proof.
 functional induction inter s1 s2; split_tac x1.
Qed.

(** diff *)

Instance diff_avl s1 s2 `{Avl s1, Avl s2} : Avl (diff s1 s2).
Proof.
 functional induction diff s1 s2; split_tac x1.
Qed.

(** union *)

Instance union_avl s1 s2 `{Avl s1, Avl s2} : Avl (union s1 s2).
Proof.
 functional induction union s1 s2; split_tac x1.
Qed.

(** filter *)

Instance filter_avl f s `{Avl s} : Avl (filter f s).
Proof.
 induction s; simpl; auto. inv_avl. destruct (f _); auto_tc.
Qed.

(** partition *)

Instance partition_avl_1 f s `{Avl s} : Avl (partition f s)#1.
Proof.
 induction s; simpl; auto. inv_avl.
 destruct (partition f s1), (partition f s2), (f _); simpl; auto_tc.
Qed.

Instance partition_avl_2 f s `{Avl s} : Avl (partition f s)#2.
Proof.
 induction s; simpl; auto. inv_avl.
 destruct (partition f s1), (partition f s2), (f _); simpl; auto_tc.
Qed.

End AvlProofs.

(** * Encapsulation

   We can implement [S] with balanced binary search trees.
   When compared to [MSetAVL], we maintain here two invariants
   (bst and avl) instead of only bst, which is enough for fulfilling
   the MSet interface.
*)

Module IntMake (I:Int)(X: OrderedType) <: S with Module E := X.

 Module E := X.
 Module Import Raw := AvlProofs I X.

 Record t_ := Mkt
   { this :> tree;
     is_bst : Ok this;
     is_avl : Avl this }.
 Arguments Mkt this {is_bst} {is_avl}.

 Definition t := t_.
 Definition elt := E.t.

 Existing Instance is_bst.
 Existing Instance is_avl.
 Existing Class bst.
 Existing Class avl.

 (** Functions *)

 Definition mem (x:elt)(s:t) : bool := mem x s.
 Definition empty : t := Mkt empty.
 Definition is_empty (s:t) : bool := is_empty s.
 Definition singleton (x:elt) : t := Mkt (singleton x).
 Definition add (x:elt)(s:t) : t := Mkt (add x s).
 Definition remove (x:elt)(s:t) : t := Mkt (remove x s).
 Definition inter (s s':t) : t := Mkt (inter s s').
 Definition union (s s':t) : t := Mkt (union s s').
 Definition diff (s s':t) : t := Mkt (diff s s').
 Definition elements (s:t) : list elt := elements s.
 Definition min_elt (s:t) : option elt := min_elt s.
 Definition max_elt (s:t) : option elt := max_elt s.
 Definition choose (s:t) : option elt := choose s.
 Definition fold {B : Type} (f : elt -> B -> B) (s:t) : B -> B := fold f s.
 Definition cardinal (s:t) : nat := cardinal s.
 Definition filter (f : elt -> bool) (s:t) : t := Mkt (filter f s).
 Definition for_all (f : elt -> bool) (s:t) : bool := for_all f s.
 Definition exists_ (f : elt -> bool) (s:t) : bool := exists_ f s.
 Definition partition (f : elt -> bool) (s:t) : t * t :=
   let p := partition f s in (Mkt (fst p), Mkt (snd p)).

 Definition equal (s s':t) : bool := equal s s'.
 Definition subset (s s':t) : bool := subset s s'.

 Definition compare (s s':t) := compare s s'.

 (** Predicates *)

 Definition In (x : elt) (s : t) : Prop := In x s.
 Definition Equal (s s':t) : Prop := forall a : elt, In a s <-> In a s'.
 Definition Subset (s s':t) : Prop := forall a : elt, In a s -> In a s'.
 Definition Empty (s:t) : Prop := forall a : elt, ~ In a s.
 Definition For_all (P : elt -> Prop) (s:t) : Prop := forall x, In x s -> P x.
 Definition Exists (P : elt -> Prop) (s:t) : Prop := exists x, In x s /\ P x.

 Instance In_compat : Proper (E.eq==>Logic.eq==>iff) In.
 Proof. repeat red. intros; apply In_compat; congruence. Qed.

 Definition eq (s s':t) : Prop := Equal s s'.
 Definition lt (s s':t) : Prop := lt s s'.

 Instance eq_equiv : Equivalence eq.
 Proof. firstorder. Qed.

 Definition eq_dec : forall (s s':t), { eq s s' }+{ ~eq s s' }.
 Proof.
  intros (s,Bs,As) (s',Bs',As').
  change ({Raw.Equal s s'}+{~Raw.Equal s s'}).
  destruct (Raw.equal s s') as [ ] eqn:H; [left|right];
   rewrite <- equal_spec; congruence.
 Defined.

 Instance lt_strorder : StrictOrder lt.
 Proof. constructor ; unfold lt; red.
   unfold complement. red. intros. apply (irreflexivity H).
   intros. transitivity y; auto.
 Qed.

 Instance lt_compat : Proper (eq==>eq==>iff) lt.
 Proof.
 repeat red. unfold eq, lt.
 intros (s1,B1,A1) (s2,B2,A2) E (s1',B1',A1') (s2',B2',A2') E'; simpl.
 change (Raw.eq s1 s2) in E.
 change (Raw.eq s1' s2') in E'.
 rewrite E,E'; intuition.
 Qed.

 (* Specs *)

 Section Specs.
 Variable s s' s'': t.
 Variable x y : elt.
 Variable f : elt -> bool.
 Notation compatb := (Proper (E.eq==>Logic.eq)) (only parsing).

 Lemma mem_spec : mem x s = true <-> In x s.
 Proof. exact (@mem_spec _ _ _). Qed.
 Lemma equal_spec : equal s s' = true <-> Equal s s'.
 Proof. exact (@equal_spec _ _ _ _). Qed.
 Lemma subset_spec : subset s s' = true <-> Subset s s'.
 Proof. exact (@subset_spec _ _ _ _). Qed.
 Lemma empty_spec : Empty empty.
 Proof. exact empty_spec. Qed.
 Lemma is_empty_spec : is_empty s = true <-> Empty s.
 Proof. exact (@is_empty_spec _). Qed.
 Lemma add_spec : In y (add x s) <-> E.eq y x \/ In y s.
 Proof. exact (@add_spec _ _ _ _). Qed.
 Lemma remove_spec : In y (remove x s) <-> In y s /\ ~E.eq y x.
 Proof. exact (@remove_spec _ _ _ _). Qed.
 Lemma singleton_spec : In y (singleton x) <-> E.eq y x.
 Proof. exact (@singleton_spec _ _). Qed.
 Lemma union_spec : In x (union s s') <-> In x s \/ In x s'.
 Proof. exact (@union_spec _ _ _ _ _). Qed.
 Lemma inter_spec : In x (inter s s') <-> In x s /\ In x s'.
 Proof. exact (@inter_spec _ _ _ _ _). Qed.
 Lemma diff_spec : In x (diff s s') <-> In x s /\ ~In x s'.
 Proof. exact (@diff_spec _ _ _ _ _). Qed.
 Lemma fold_spec : forall (A : Type) (i : A) (f : elt -> A -> A),
     fold f s i = fold_left (fun a e => f e a) (elements s) i.
 Proof. exact (@fold_spec _). Qed.
 Lemma cardinal_spec : cardinal s = length (elements s).
 Proof. exact (@cardinal_spec s _). Qed.
 Lemma filter_spec : compatb f ->
   (In x (filter f s) <-> In x s /\ f x = true).
 Proof. exact (@filter_spec _ _ _). Qed.
 Lemma for_all_spec : compatb f ->
   (for_all f s = true <-> For_all (fun x => f x = true) s).
 Proof. exact (@for_all_spec _ _). Qed.
 Lemma exists_spec : compatb f ->
   (exists_ f s = true <-> Exists (fun x => f x = true) s).
 Proof. exact (@exists_spec _ _). Qed.
 Lemma partition_spec1 : compatb f -> Equal (fst (partition f s)) (filter f s).
 Proof. exact (@partition_spec1 _ _). Qed.
 Lemma partition_spec2 : compatb f ->
   Equal (snd (partition f s)) (filter (fun x => negb (f x)) s).
 Proof. exact (@partition_spec2 _ _). Qed.
 Lemma elements_spec1 : InA E.eq x (elements s) <-> In x s.
 Proof. exact (@elements_spec1 _ _). Qed.
 Lemma elements_spec2w : NoDupA E.eq (elements s).
 Proof. exact (@elements_spec2w _ _). Qed.
 Lemma choose_spec1 : choose s = Some x -> In x s.
 Proof. exact (@choose_spec1 _ _). Qed.
 Lemma choose_spec2 : choose s = None -> Empty s.
 Proof. exact (@choose_spec2 _). Qed.

 Lemma compare_spec : CompSpec eq lt s s' (compare s s').
 Proof. unfold compare; destruct (@compare_spec s s' _ _); auto. Qed.
 Lemma elements_spec2 : sort X.lt (elements s).
 Proof. exact (@elements_spec2 _ _). Qed.
 Lemma min_elt_spec1 : min_elt s = Some x -> In x s.
 Proof. exact (@min_elt_spec1 _ _). Qed.
 Lemma min_elt_spec2 : min_elt s = Some x -> In y s -> ~ X.lt y x.
 Proof. exact (@min_elt_spec2 _ _ _ _). Qed.
 Lemma min_elt_spec3 : min_elt s = None -> Empty s.
 Proof. exact (@min_elt_spec3 _). Qed.
 Lemma max_elt_spec1 : max_elt s = Some x -> In x s.
 Proof. exact (@max_elt_spec1 _ _). Qed.
 Lemma max_elt_spec2 : max_elt s = Some x -> In y s -> ~ X.lt x y.
 Proof. exact (@max_elt_spec2 _ _ _ _). Qed.
 Lemma max_elt_spec3 : max_elt s = None -> Empty s.
 Proof. exact (@max_elt_spec3 _). Qed.
 Lemma choose_spec3 :
    choose s = Some x -> choose s' = Some y -> Equal s s' -> X.eq x y.
  Proof. exact (@choose_spec3 _ _ _ _ _ _). Qed.

End Specs.
End IntMake.

(* For concrete use inside Coq, we propose an instantiation of [Int] by [Z]. *)

Module Make (X: OrderedType) <: S with Module E := X
 :=IntMake(Z_as_Int)(X).

Require Import Recdef.

Module OcamlOps (Import I:Int)(X:OrderedType).
Module Import Raw := AvlProofs I X.
Import II.
Local Open Scope pair_scope.
Local Open Scope nat_scope.
Local Hint Resolve MX.eq_refl MX.eq_trans MX.lt_trans @ok.
Local Hint Immediate MX.eq_sym.
Local Hint Unfold In lt_tree gt_tree.
Local Hint Constructors InT bst.
Local Hint Unfold Ok.
Local Hint Resolve lt_leaf gt_leaf lt_tree_node gt_tree_node.

Ltac avl_nn' h :=
  let t := type of h in
  match type of t with
   | Prop => avl_nn h
   | _ => match goal with H : Avl h |- _ => avl_nn H end
  end.

(** Properties of cardinal *)

Lemma bal_cardinal : forall l x r,
 cardinal (bal l x r) = S (cardinal l + cardinal r).
Proof.
 intros l x r; functional induction bal l x r; intros; clearf;
 simpl; auto with arith; romega with *.
Qed.

Lemma add_cardinal : forall x s,
 cardinal (add x s) <= S (cardinal s).
Proof.
 induct s x; simpl; auto with arith;
 rewrite bal_cardinal; romega with *.
Qed.

Lemma join_cardinal : forall l x r,
 cardinal (join l x r) <= S (cardinal l + cardinal r).
Proof.
 join_tac; clearf; auto with arith.
 - simpl; apply add_cardinal.
 - simpl; destruct X.compare; simpl.
   * auto with arith.
   * generalize (bal_cardinal (add x ll) lx lr) (add_cardinal x ll);
     romega with *.
   * generalize (bal_cardinal ll lx (add x lr)) (add_cardinal x lr);
     romega with *.
 - generalize (bal_cardinal ll lx (join lr x (Node rh rl rx rr)))
  (Hlr x (Node rh rl rx rr)); simpl; romega with *.
 - simpl (S _) in *; generalize (bal_cardinal (join (Node lh ll lx lr) x rl) rx rr).
   romega with *.
Qed.

Lemma split_cardinal_1 : forall x s,
 (cardinal (split x s)#l <= cardinal s)%nat.
Proof.
 intros x s; functional induction split x s; simpl; auto.
 - romega with *.
 - rewrite e1 in IHt0; simpl in *.
   romega with *.
 - rewrite e1 in IHt0; simpl in *.
   generalize (@join_cardinal l y rl); romega with *.
Qed.

Lemma split_cardinal_2 : forall x s,
 (cardinal (split x s)#r <= cardinal s)%nat.
Proof.
 intros x s; functional induction split x s; simpl; auto.
 - romega with *.
 - rewrite e1 in IHt0; simpl in *.
   generalize (@join_cardinal rl y r); romega with *.
 - rewrite e1 in IHt0; simpl in *; romega with *.
Qed.

(** * [ocaml_union], an union faithful to the original ocaml code *)

Definition cardinal2 (s:t*t) := (cardinal s#1 + cardinal s#2)%nat.

Ltac ocaml_union_tac :=
 intros; unfold cardinal2; simpl fst in *; simpl snd in *;
 match goal with H: split ?x ?s = _ |- _ =>
  generalize (split_cardinal_1 x s) (split_cardinal_2 x s);
  rewrite H; simpl; romega with *
 end.

Function ocaml_union (s : t * t) { measure cardinal2 s } : t  :=
 match s with
  | (Leaf, Leaf) => s#2
  | (Leaf, Node _ _ _ _) => s#2
  | (Node _ _ _ _, Leaf) => s#1
  | (Node h1 l1 x1 r1, Node h2 l2 x2 r2) =>
        if ge_lt_dec h1 h2 then
          if eq_dec h2 1%I then add x2 s#1 else
          let (l2',_,r2') := split x1 s#2 in
             join (ocaml_union (l1,l2')) x1 (ocaml_union (r1,r2'))
        else
          if eq_dec h1 1%I then add x1 s#2 else
          let (l1',_,r1') := split x2 s#1 in
             join (ocaml_union (l1',l2)) x2 (ocaml_union (r1',r2))
 end.
Proof.
abstract ocaml_union_tac.
abstract ocaml_union_tac.
abstract ocaml_union_tac.
abstract ocaml_union_tac.
Defined.

Lemma ocaml_union_in : forall s y,
 Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 ->
 (InT y (ocaml_union s) <-> InT y s#1 \/ InT y s#2).
Proof.
 intros s; functional induction ocaml_union s; intros y B1 A1 B2 A2;
  simpl (@fst) in *; simpl (@snd) in *; try clear e0 e1.
 - intuition_in.
 - intuition_in.
 - intuition_in.
 - (* add x2 s#1 *)
   inv_avl.
   rewrite (height_0 l2) by (avl_nn' l2; omega_max).
   rewrite (height_0 r2) by (avl_nn' r2; omega_max).
   rewrite add_spec; intuition_in.
 - (* join (union (l1,l2')) x1 (union (r1,r2')) *)
   clear _x _x0. factornode s2.
   generalize
    (split_avl s2 x1) (@split_ok s2 x1 B2)
    (@split_spec1 s2 x1 y B2) (@split_spec2 s2 x1 y B2).
   rewrite e2; simpl.
   destruct 1; destruct 1; inv_avl; invtree Ok.
   rewrite join_spec, IHt0, IHt1; auto.
   do 2 (intro Eq; rewrite Eq; clear Eq).
   destruct (X.compare_spec y x1); intuition_in.
 - (* add x1 s#2 *)
   inv_avl.
   rewrite (height_0 l1) by (avl_nn' l1; omega_max).
   rewrite (height_0 r1) by (avl_nn' r1; omega_max).
   rewrite add_spec; auto; intuition_in.
 - (* join (union (l1',l2)) x1 (union (r1',r2)) *)
   clear _x _x0. factornode s1.
   generalize
    (split_avl s1 x2) (@split_ok s1 x2 B1)
    (@split_spec1 s1 x2 y B1) (@split_spec2 s1 x2 y B1).
   rewrite e2; simpl.
   destruct 1; destruct 1; inv_avl; invtree Ok.
   rewrite join_spec, IHt0, IHt1; auto.
   do 2 (intro Eq; rewrite Eq; clear Eq).
   destruct (X.compare_spec y x2); intuition_in.
Qed.

Lemma ocaml_union_bst : forall s,
 Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 -> Ok (ocaml_union s).
Proof.
 intros s; functional induction ocaml_union s; intros B1 A1 B2 A2;
  simpl @fst in *; simpl @snd in *; try clear e0 e1;
  try apply add_ok; auto.
 - (* join (union (l1,l2')) x1 (union (r1,r2')) *)
 clear _x _x0; factornode s2.
 generalize (split_avl s2 x1) (@split_ok _ x1 B2)
  (@split_spec1 s2 x1)(@split_spec2 s2 x1).
 rewrite e2; simpl.
 destruct 1; destruct 1; intros.
 invtree Ok; inv_avl.
 apply join_ok; auto.
 intro y; rewrite ocaml_union_in, H3; intuition_in.
 intro y; rewrite ocaml_union_in, H4; intuition_in.
 - (* join (union (l1',l2)) x1 (union (r1',r2)) *)
 clear _x _x0; factornode s1.
 generalize (split_avl s1 x2) (@split_ok _ x2 B1)
  (@split_spec1 s1 x2)(@split_spec2 s1 x2).
 rewrite e2; simpl.
 destruct 1; destruct 1; intros.
 invtree Ok; inv_avl.
 apply join_ok; auto.
 intro y; rewrite ocaml_union_in, H3; intuition_in.
 intro y; rewrite ocaml_union_in, H4; intuition_in.
Qed.

Lemma ocaml_union_avl : forall s,
 Avl s#1 -> Avl s#2 -> Avl (ocaml_union s).
Proof.
 intros s; functional induction ocaml_union s;
  simpl @fst in *; simpl @snd in *; auto_tc.
 intros A1 A2; generalize (@split_avl _ x1 A2); rewrite e2; simpl.
 inv_avl; destruct 1; auto_tc.
 intros A1 A2; generalize (@split_avl _ x2 A1); rewrite e2; simpl.
 inv_avl; destruct 1; auto_tc.
Qed.

Lemma ocaml_union_alt : forall s, Ok s#1 -> Avl s#1 -> Ok s#2 -> Avl s#2 ->
 Equal (ocaml_union s) (union s#1 s#2).
Proof.
 red; intros; rewrite ocaml_union_in, union_spec; simpl; intuition.
Qed.

(** * [ocaml_subset], a subset faithful to the original ocaml code *)

Function ocaml_subset (s:t*t) { measure cardinal2 s } : bool :=
 match s with
  | (Leaf, _) => true
  | (Node _ _ _ _, Leaf) => false
  | (Node _ l1 x1 r1, Node _ l2 x2 r2) =>
     match X.compare x1 x2 with
      | Eq => ocaml_subset (l1,l2) && ocaml_subset (r1,r2)
      | Lt => ocaml_subset (Node 0%I l1 x1 Leaf, l2) && ocaml_subset (r1,s#2)
      | Gt => ocaml_subset (Node 0%I Leaf x1 r1, r2) && ocaml_subset (l1,s#2)
     end
 end.

Proof.
 intros; unfold cardinal2; simpl; abstract romega with *.
 intros; unfold cardinal2; simpl; abstract romega with *.
 intros; unfold cardinal2; simpl; abstract romega with *.
 intros; unfold cardinal2; simpl; abstract romega with *.
 intros; unfold cardinal2; simpl; abstract romega with *.
 intros; unfold cardinal2; simpl; abstract romega with *.
Defined.

Ltac ocaml_subset_tac :=
 simpl in *; invtree Ok; rewrite andb_true_iff;
 match goal with _ : X.compare ?x1 ?x2 = _ |- _ =>
  destruct (X.compare_spec x1 x2); try discriminate
 end;
 repeat
  (match goal with H : context [ocaml_subset] |- _ => rewrite H; clear H end);
 unfold Subset; intuition_in;
 match goal with
  | H : forall a, InT a _ -> InT a ?s |- InT ?a _ =>
    assert (InT a s) by auto; intuition_in; order
  | _ => apply IsRoot; order
 end.

Lemma ocaml_subset_12 : forall s,
 Ok s#1 -> Ok s#2 ->
 (ocaml_subset s = true <-> Subset s#1 s#2).
Proof.
 intros s; functional induction ocaml_subset s; simpl; intros B1 B2.
 - intuition.
   red; auto; inversion 1.
 - split; intros; try discriminate.
   assert (H': In _x1 Leaf) by auto; inversion H'.
 - ocaml_subset_tac.
 - ocaml_subset_tac.
 - ocaml_subset_tac.
Qed.

Lemma ocaml_subset_alt : forall s, Ok s#1 -> Ok s#2 ->
 ocaml_subset s = subset s#1 s#2.
Proof.
 intros.
 generalize (ocaml_subset_12 _ H H0). rewrite <- subset_spec by auto.
 destruct ocaml_subset; destruct subset; intuition.
Qed.

(** [ocaml_compare], a compare faithful to the original ocaml code *)

(** termination of [compare_aux] *)

Fixpoint cardinal_e e := match e with
  | End => 0
  | More _ s r => S (cardinal s + cardinal_e r)
 end.

Lemma cons_cardinal_e : forall s e,
 cardinal_e (cons s e) = cardinal s + cardinal_e e.
Proof.
 induction s; simpl; intros; auto.
 rewrite IHs1; simpl; rewrite <- plus_n_Sm; auto with arith.
Qed.

Definition cardinal_e_2 e := cardinal_e e#1 + cardinal_e e#2.

Function ocaml_compare_aux
 (e:enumeration*enumeration) { measure cardinal_e_2 e } : comparison :=
 match e with
 | (End,End) => Eq
 | (End,More _ _ _) => Lt
 | (More _ _ _, End) => Gt
 | (More x1 r1 e1, More x2 r2 e2) =>
       match X.compare x1 x2 with
        | Eq => ocaml_compare_aux (cons r1 e1, cons r2 e2)
        | Lt => Lt
        | Gt => Gt
       end
 end.

Proof.
intros; unfold cardinal_e_2; simpl;
abstract (do 2 rewrite cons_cardinal_e; romega with * ).
Defined.

Definition ocaml_compare s1 s2 :=
 ocaml_compare_aux (cons s1 End, cons s2 End).

Local Hint Constructors L.lt_list.

Lemma ocaml_compare_aux_Cmp : forall e,
 Cmp (ocaml_compare_aux e) (flatten_e e#1) (flatten_e e#2).
Proof.
 intros e; functional induction ocaml_compare_aux e; simpl; intros;
  try constructor; auto;
  try destruct (X.compare_spec x1 x2); try discriminate; auto.
 reflexivity.
 apply L.cons_CompSpec; trivial. now rewrite <- !cons_1.
Qed.

Lemma ocaml_compare_Cmp : forall s1 s2,
 Cmp (ocaml_compare s1 s2) (elements s1) (elements s2).
Proof.
 unfold ocaml_compare; intros.
 assert (H1:=cons_1 s1 End).
 assert (H2:=cons_1 s2 End).
 simpl in *; rewrite <- app_nil_end in *; rewrite <-H1,<-H2.
 apply (@ocaml_compare_aux_Cmp (cons s1 End, cons s2 End)).
Qed.

Lemma ocaml_compare_alt : forall s1 s2, Ok s1 -> Ok s2 ->
 ocaml_compare s1 s2 = compare s1 s2.
Proof.
 intros s1 s2 B1 B2.
 generalize (ocaml_compare_Cmp s1 s2)(compare_Cmp s1 s2).
 destruct ocaml_compare; destruct compare; auto; intros; exfalso;
 inversion_clear H; inversion_clear H0; rewrite <- ?eq_Leq in *;
 repeat match goal with
  | H : L.lt (elements ?s1) (elements ?s2) |- _ =>
    assert (lt s1 s2) by (exists s1; exists s2; intuition); clear H
 end.
 rewrite H1 in H0. now apply StrictOrder_Irreflexive with s2.
 rewrite H1 in H0. now apply StrictOrder_Irreflexive with s2.
 rewrite H in H0. now apply StrictOrder_Irreflexive with s2.
 apply StrictOrder_Irreflexive with s2. now transitivity s1.
 rewrite H in H0. now apply StrictOrder_Irreflexive with s2.
 apply StrictOrder_Irreflexive with s2. now transitivity s1.
Qed.

(** * Equality test *)

Definition ocaml_equal s1 s2 : bool :=
 match ocaml_compare s1 s2 with
  | Eq => true
  | _ => false
 end.

Lemma ocaml_equal_alt : forall s1 s2, Ok s1 -> Ok s2 ->
 ocaml_equal s1 s2 = equal s1 s2.
Proof.
intros; unfold ocaml_equal, equal; rewrite ocaml_compare_alt; auto.
Qed.

Lemma ocaml_equal_1 : forall s1 s2, Ok s1 -> Ok s2 ->
 Equal s1 s2 -> ocaml_equal s1 s2 = true.
Proof.
intros. rewrite ocaml_equal_alt; trivial. now apply equal_spec.
Qed.

Lemma ocaml_equal_2 : forall s1 s2,
 ocaml_equal s1 s2 = true -> Equal s1 s2.
Proof.
unfold ocaml_equal; intros s1 s2 E.
generalize (ocaml_compare_Cmp s1 s2);
 destruct ocaml_compare; auto; try discriminate.
inversion 1. now apply eq_Leq.
Qed.

End OcamlOps.


Require Import Setoid.
Require Import Lia.

Axiom double_neg : forall P, P <-> ~~P.
Lemma fold_not : forall (P: Prop), (P -> False) <-> ~P. intuition auto. Defined.
Axiom forall_exists_duality1 : forall {T} (P: T -> Prop), ~ (exists x, P x) <-> (forall x, ~ P x).
Axiom forall_exists_duality2 : forall {T} (P: T -> Prop), ~ (forall x, P x) <-> (exists x, ~ P x).
Axiom DeMorgan1 : forall (P Q : Prop), ~(P /\ Q) <-> (~P \/ ~Q).
Axiom DeMorgan2 : forall (P Q : Prop), ~(P \/ Q) <-> (~P /\ ~Q).

Ltac classical :=
  repeat match goal with
  | [ H : context[_ -> False] |- _ ] => rewrite (fold_not) in H (* sometimes intuition leaves us with negations like this. *)
  | [ H : context[~(~ _)]|- _ ] => rewrite <-double_neg in H
  | [ H : _ |- _ ] => rewrite DeMorgan1 in H
  | [ H : _ |- _ ] => rewrite DeMorgan2 in H
  | [ H: _ |- _] => erewrite forall_exists_duality1 in H
  | [ H: _ |- _] => erewrite forall_exists_duality2 in H
  | [ H : _ |- context[_ -> False] ] => rewrite (fold_not) (* sometimes intuition leaves us with negations like this. *)
  | [ H : _ |- context[~(~ _)] ] => rewrite <-double_neg
  | [ H : _ |- _ ] => rewrite DeMorgan1
  | [ H : _ |- _ ] => rewrite DeMorgan2
  | [ H: _ |- _] => erewrite forall_exists_duality1
  | [ H: _ |- _] => erewrite forall_exists_duality2
  end; try solve [intuition auto].

Section LTLdef.
  Context {T: Type}.
  Inductive LTL : Type :=
  injp_ltl : (T -> Prop) -> LTL
  | false_ltl : LTL
  | true_ltl : LTL
  | imp_ltl : LTL -> LTL -> LTL
  | until_ltl : LTL -> LTL -> LTL
  | next_ltl : LTL -> LTL.
  Definition TemInt : Type := nat -> T.
  Notation "φ U- ψ" := (until_ltl φ ψ) (at level 10).
  Definition from (k: nat): TemInt -> TemInt :=
      fun ζ n =>
        ζ (n+k).
  Notation "ζ ^^ k" := (from k ζ) (at level 10).

  Reserved Notation "ζ ⊨ φ" (at level 50, no associativity).
  Fixpoint models (φ : LTL) (ζ : TemInt) {struct φ}: Prop :=
      match φ with
      | injp_ltl p =>
        p (ζ 0)
      | imp_ltl ψ π =>
        (~(ζ ⊨ ψ) \/ (ζ ⊨ π))
      | next_ltl ψ =>
        (from 1 ζ) ⊨ ψ
      | until_ltl ψ π =>
        (exists (i:nat),
          ζ ^^ i ⊨ π
          /\ (forall j, j < i -> ζ ^^ j ⊨ ψ))
      | false_ltl =>
        False
      | true_ltl =>
        True
      end
  where "ζ ⊨ φ" := (models φ ζ).

  Definition not_ltl (φ : LTL) : LTL := imp_ltl φ false_ltl.
  Definition ev_ltl (φ : LTL): LTL := true_ltl U- φ.
  Definition always_ltl (φ : LTL): LTL := not_ltl (ev_ltl (not_ltl φ)).
  Definition and_ltl (ϕ ψ : LTL) : LTL := not_ltl (imp_ltl ϕ (not_ltl ψ)).

  Theorem and_good : forall ζ ϕ ψ, ζ ⊨ ϕ /\ ζ ⊨ ψ <-> ζ ⊨ (and_ltl ϕ ψ).
  Proof.
    intros.
    split.
    { (* fwd *)
      intro.
      unfold  and_ltl,not_ltl.
      cbn.
      left.
      intro.
      repeat destruct H0; destruct H; auto.
    }
    {
      intro.
      split.
      {
        inversion H;
        cbn in H0;
        intuition auto;
        classical.
      }
      {
        inversion H; cbn in *; intuition auto; classical.
      }
    }
  Defined.

  Lemma ltl_not_good : forall ζ φ, ~ ζ ⊨ φ <-> ζ ⊨ (not_ltl φ).
    Proof.
      (* Very lightly modified from a proof generated by GPT-3/copilot. *)
      intros.
      split.
      {
        intro H.
        unfold not_ltl.
        lazy.
        left.
        intro.
        repeat destruct H0; destruct H; auto.
      }
      {
        intro.
        inversion H; cbn in *; intuition auto; classical.
      }
    Defined.

  Theorem always_iff_loop_inv : forall (φ : LTL) (ζ : TemInt),
    ζ ⊨ (always_ltl φ)
    <-> (exists (i : nat),
          (forall k, k >= i -> ζ ^^ k ⊨ φ -> ζ ^^ (k+1) ⊨ φ) /\ (forall (j : nat), j <= i -> ζ ^^ j ⊨ φ)).
  Proof.
    intros.
    split.
    {
      intros H.
      exists 0.
      split; intros.
      {
        simpl in H.
        classical.
        destruct H; try solve [intuition auto].
        specialize (H (k+1)).
        classical.
        repeat destruct H; solve [intuition auto].
      }
      {
        inversion H0.
        simpl in H.
        classical.
        destruct H; try solve [intuition auto].
        specialize (H 0).
        classical.
        repeat destruct H; try solve [intuition auto].
      }
    }
    {
     intros H.
     left.
     simpl.
     destruct H as [i [Hpres Hinit]].
     simpl.
     repeat (progress classical || intro).
     left.
     split; [|solve[intuition auto]].
     Require Import Coq.Arith.Compare_dec.
     pose proof (lt_eq_lt_dec x i) as Hcompxi.
     repeat match goal with
            | [ H : context[{_} + {_}] |- _] => destruct H as [H | H]
            end; try solve [eapply Hinit;lia].
     {
      assert (Hstronger : forall n, ζ ^^ (i+n) ⊨ φ).
      {
        induction n.
        {
          unshelve erewrite (_ : i + 0 = i). lia.
          eapply Hinit.
          auto.
        }
        {
          unshelve erewrite (_ : i + S n = (i + n) + 1). lia.
          eapply Hpres.
          lia.
          auto.
        }
      }
      remember (x - i) as diff.
      unshelve erewrite (_ : x = i + diff); try solve[lia].
      auto.
     }
    }
Defined.
End LTLdef.

Record Mealy : Type := mkMealy {
                           Σ : Type
                         ; Q : Type
                         ; δ : Q -> Σ -> Q * Σ
                         ; Q₀ : Q
                         }.

Fixpoint MealyTrace' (M : Mealy) (I : nat -> Σ M) (n : nat) {struct n}: (Q M) * (Σ M) :=
    match n with
    | 0 => (δ M) (Q₀ M) (I 0)
    | S n' => let (Q', _) := MealyTrace' M I n' in
             (δ M) Q' (I n)
    end.

Definition MealyTrace (M : Mealy) (I : nat -> Σ M) : @TemInt (Q M * Σ M) :=
    fun n => MealyTrace' M I n.


From Coq Require Import Ring.
From stdpp Require Import base.
From BY Require Export Hierarchy.Definitions.
From BY.Hierarchy Require Import Group AbelianGroup Monoid.

Section Ring.
  Local Open Scope ring_scope.

  Class Ring A `{Equiv A, Op1 A, Op2 A, Id1 A, Id2 A, Inv1 A} :=
    {
      ring_ab_grp :> @AbelianGroup _ _ (+) 0 (-);
      ring_mon :> @Monoid _ _ [*] 1;
      ring_distr_l :> LeftDistr (≡) [*] (+);
      ring_distr_r :> RightDistr (≡) [*] (+)
    }.

  Class RingCongruence `{Ring A} (rel : relation A) :=
    {
      ring_cong_equiv :> Equivalence rel;
      ring_cong_op1_proper :> Proper (rel ==> rel ==> rel) (+);
      ring_cong_op2_proper :> Proper (rel ==> rel ==> rel) [*];
      ring_cong_inv_proper :> Proper (rel ==> rel) (-)
    }.

  Context
    `{Ring A}.
  Local Instance : @Group A _ (+) 0 (-). sub_class_tac. Qed.

  (* Instance : @AbelianGroup A _ (+) 0 (-) := _. *)

  (* split. *)
  (* repeat split; try apply _; try exact _. exact _. *)

  (* Global Instance mul_1_r : @RightId _ _ ring_op 1 := right_identity. *)
  (* Global Instance mul_1_l : @LeftIdentity _ _ ring_op 1 := left_identity. *)

  (* Global Instance mul_assoc : @Associative _ ring_op := associative. *)

  (* Global Instance mul_add_distr_l : LeftDistributive := left_distributive. *)
  (* Global Instance mul_add_distr_r : RightDistributive := right_distributive. *)

  Lemma mul_0_r : forall x : A, x * 0 ≡ 0.
  Proof.
    intros.
    setoid_replace (x * 0) with (x * 0 + 0) by (symmetry; apply (right_id 0 (+))).
    setoid_replace 0 with (x * 0 - x * 0) at 3 by (symmetry; apply (right_inv 0 (-) (+))).
    setoid_rewrite (assoc (+)).
    setoid_rewrite <- (left_distr [*] (+)).
    setoid_rewrite (left_id 0 (+)).
    apply (right_inv 0 (-) (+)).
  Qed.

  Lemma mul_0_l : forall x, 0 * x ≡ 0.
  Proof.
    intros.
    setoid_replace (0 * x) with (0 * x + 0) by (symmetry; apply (right_id 0 (+))).
    setoid_replace 0 with (0 * x - 0 * x) at 3 by (symmetry; apply (right_inv 0 (-) (+))).
    setoid_rewrite (assoc (+)).
    setoid_rewrite <- (right_distr [*] (+)).
    setoid_rewrite (left_id 0 (+)).
    apply (right_inv 0 (-) (+)).
  Qed.

  Definition ring_opp_unique_l : forall x y : A, y + x ≡ 0 -> y ≡ - x := grp_inv_unique_l.

  Lemma opp_mul_l : forall x y, - (x * y) ≡ - x * y.
  Proof.
    intros. symmetry.
    apply ring_opp_unique_l.
    rewrite <- (right_distr [*] (+)).
    setoid_rewrite (left_inv 0 (-) (+)).
    apply mul_0_l.
  Qed.

  Lemma opp_mul_r : forall x y, - (x * y) ≡ x * - y.
  Proof.
    intros. symmetry.
    apply ring_opp_unique_l.
    rewrite <- (left_distr [*] (+)).
    setoid_rewrite (left_inv 0 (-) (+)).
    apply mul_0_r.
  Qed.

End Ring.


(** * Tactics: More Basic Tactics *)

(** This chapter introduces several additional proof strategies
    and tactics that allow us to begin proving more interesting
    properties of functional programs.  We will see:

    - how to use auxiliary lemmas in both "forward-style" and
      "backward-style" proofs;
    - how to reason about data constructors (in particular, how to use
      the fact that they are injective and disjoint);
    - how to strengthen an induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis. *)

Require Export Poly.

(* ################################################################# *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    _exactly_ the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.

(** Here, we could finish with "[rewrite -> eq2.  reflexivity.]" as we
    have done several times before.  We can achieve the same effect in
    a single step by using the [apply] tactic instead: *)

  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
     n = m  ->
     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that binds some _universal variables_.  When
    Coq matches the current goal against the conclusion of [H], it
    will try to find appropriate values for these variables.  For
    example, when we do [apply eq2] in the following proof, the
    universal variable [q] in [eq2] gets instantiated with [n] and [r]
    gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** **** Exercise: 2 stars, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal exactly -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  simpl.

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

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

(** **** Exercise: 3 stars (apply_exercise1)  *)
(** (_Hint_: You can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [SearchAbout] is
    your friend.) *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied?

(* FILL IN HERE *)
*)
(** [] *)

(* ################################################################# *)
(** * The [apply ... with ...] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a,b]] to [[e,f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.

(** Since this is a common pattern, we might like to pull it out
    as a lemma recording, once and for all, the fact that equality is
    transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
  reflexivity.  Qed.

(** Now, we should be able to use [trans_eq] to prove the above
    example.  However, to do this we need a slight refinement of the
    [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.

(** If we simply tell Coq [apply trans_eq] at this point, it can
    tell (by matching the goal against the conclusion of the lemma)
    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and
    [o] with [[e,f]].  However, the matching process doesn't determine
    an instantiation for [m]: we have to supply one explicitly by
    adding [with (m:=[c,d])] to the invocation of [apply]. *)

  apply trans_eq with (m:=[c;d]).
  apply eq1. apply eq2.   Qed.

(** Actually, we usually don't have to include the name [m] in
    the [with] clause; Coq is often smart enough to figure out which
    instantiation we're giving. We could instead write: [apply
    trans_eq with [c;d]]. *)

(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * The [inversion] Tactic *)

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.

    It is obvious from this definition that every number has one of
    two forms: either it is the constructor [O] or it is built by
    applying the constructor [S] to another number.  But there is more
    here than meets the eye: implicit in the definition (and in our
    informal understanding of how datatype declarations work in other
    programming languages) are two more facts:

    - The constructor [S] is _injective_.  That is, if [S n = S m], it
      must be the case that [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n].

    Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor
    is injective and [nil] is different from every non-empty list.
    For booleans, [true] and [false] are different.  (Since neither
    [true] nor [false] take any arguments, their injectivity is not
    interesting.)  And so on. *)

(** Coq provides a tactic called [inversion] that allows us to
    exploit these principles in proofs. To see how to use it, let's
    show explicitly that the [S] constructor is injective: *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [inversion H] at this point, we are asking Coq to
    generate all equations that it can infer from [H] as additional
    hypotheses, replacing variables in the goal as it goes. In the
    present example, this amounts to adding a new hypothesis [H1 : n =
    m] and replacing [n] by [m] in the goal. *)

  inversion H.
  reflexivity.
Qed.

(** Here's a more interesting example that shows how multiple
    equations can be derived at once. *)

Theorem inversion_ex1 : forall (n m o : nat),
  [n; m] = [o; o] ->
  [n] = [m].
Proof.
  intros n m o H. inversion H. reflexivity. Qed.

(** We can name the equations that [inversion] generates with an
    [as ...] clause: *)

Theorem inversion_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.

(** **** Exercise: 1 star (inversion_ex3)  *)
Example inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  y :: l = x :: j ->
  x = y.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately.  Consider the following proof: *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'].
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming
    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
    clearly contradictory!  The way forward lies in the assumption.
    After simplifying the goal state, we see that [beq_nat 0 (S n') =
    true] has become [false = true]: *)

  - (* n = S n' *)
    simpl.

(** If we use [inversion] on this hypothesis, Coq notices that
    the subgoal we are working on is impossible, and therefore removes
    it from further consideration. *)

    intros H. inversion H. Qed.

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

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

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

(** If you find the principle of explosion confusing, remember
    that these proofs are not actually showing that the conclusion of
    the statement holds.  Rather, they are arguing that, if the
    nonsensical situation described by the premise did somehow arise,
    then the nonsensical conclusion would follow.  We'll explore the
    principle of explosion of more detail in the next chapter. *)

(** **** Exercise: 1 star (inversion_ex6)  *)
Example inversion_ex6 : forall (X : Type)
                          (x y z : X) (l j : list X),
  x :: y :: l = [] ->
  y :: l = z :: j ->
  x = z.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To summarize this discussion, suppose [H] is a hypothesis in the
    context or a previously proven lemma of the form

        c a1 a2 ... an = d b1 b2 ... bm

    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] has the following effect:

    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know that [a1 = b1], [a2 =
      b2], etc.  The [inversion H] adds these facts to the context and
      tries to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory, and the current goal doesn't have to be
      considered at all.  In this case, [inversion H] marks the
      current goal as completed and pops it off the goal stack. *)

(** The injectivity of constructors allows us to reason that
    [forall (n m : nat), S n = S m -> n = m].  The converse of this
    implication is an instance of a more general fact about both
    constructors and functions, which we will find useful in a few
    places below: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
  x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.

(* ################################################################# *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic [simpl in H] performs simplification in
    the hypothesis named [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     beq_nat (S n) (S m) = b  ->
     beq_nat n m = b.
Proof.
  intros n m b H. simpl in H. apply H.  Qed.

(** Similarly, [apply L in H] matches some conditional statement
    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the
    context.  However, unlike ordinary [apply] (which rewrites a goal
    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]
    against [L1] and, if successful, replaces it with [L2].

    In other words, [apply L in H] gives us a form of "forward
    reasoning": from [L1 -> L2] and a hypothesis matching [L1], it
    produces a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning": it says that if we know [L1->L2] and we are
    trying to prove [L2], it suffices to prove [L1].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly3' : forall (n : nat),
  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
  true = beq_nat n 5  ->
  true = beq_nat (S (S n)) 7.
Proof.
  intros n eq H.
  symmetry in H. apply eq in H. symmetry in H.
  apply H.  Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise.  (Hint: use
    [plus_n_Sm].) *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that the [double] function is injective -- i.e.,
    that it maps different arguments to different results:

    Theorem double_injective: forall n m,
      double n = double m -> n = m.

    The way we _start_ this proof is a bit delicate: if we begin with

      intros n. induction n.

    all is well.  But if we begin it with

      intros n m. induction n.

    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *) intros eq. destruct m as [| m'].
    + (* m = O *) inversion eq.
    + (* m = S m' *) apply f_equal.

(** At this point, the induction hypothesis, [IHn'], does _not_ give us
    [n' = m'] -- there is an extra [S] in the way -- so the goal is
    not provable. *)

      Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular [n]
    and [m]..." and we now have to prove that, if [double n = double
    m] for _these particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove, for
    _all_ [n], that the proposition

      - [P n] = "if [double n = double m], then [n = m]"

    holds, by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]") and

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: it says that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular [m] --
    say, [5].  The statement is then saying that, if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help at all with proving
    [R]!  (If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing about
    whether [double n] is [10], so [Q] is useless.) *)

(** Trying to carry out this proof by induction on [n] when [m] is
    already in the context doesn't work because we are then trying to
    prove a relation involving _every_ [n] but just a _single_ [m]. *)

(** The successful proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.

  - (* n = S n' *) simpl.

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., to prove the statement for _every_ [m]), but the IH
    is correspondingly more flexible, allowing us to choose any [m] we
    like when we apply the IH. *)

    intros m eq.

(** Now we've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'].
    + (* m = O *) simpl.

(** The 0 case is trivial: *)

      inversion eq.

    + (* m = S m' *)
      apply f_equal.

(** At this point, since we are in the second branch of the [destruct
    m], the [m'] mentioned in the context is the predecessor of the
    [m] we started out talking about.  Since we are also in the [S]
    branch of the induction, this is perfect: if we instantiate the
    generic [m] in the IH with the current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. inversion eq. reflexivity. Qed.

(** What you should take away from all this is that we need to be
    careful about using induction to try to prove something too
    specific: To prove a property of [n] and [m] by induction on [n],
    it is sometimes important to leave [m] generic. *)

(** The following exercise requires the same pattern. *)

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)

(* FILL IN HERE *)
(** [] *)

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    some _rearrangement_ of quantified variables is needed.  Suppose,
    for example, that we wanted to prove [double_injective] by
    induction on [m] instead of [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *) apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (If we simply say [induction m] without
    introducing anything first, Coq will automatically introduce [n]
    for us!)  *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables out of the context and putting them
    back at the beginning of the goal.  The [generalize dependent]
    tactic does this. *)

Theorem double_injective_take2 : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. inversion eq. reflexivity. Qed.

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

    _Theorem_: For any nats [n] and [m], if [double n = double m], then
      [n = m].

    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
      any [n], if [double n = double m] then [n = m].

      - First, suppose [m = 0], and suppose [n] is a number such
        that [double n = double m].  We must show that [n = 0].

        Since [m = 0], by the definition of [double] we have [double n =
        0].  There are two cases to consider for [n].  If [n = 0] we are
        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']
        for some [n'], we derive a contradiction: by the definition of
        [double], we can calculate [double n = S (S (double n'))], but
        this contradicts the assumption that [double n = 0].

      - Second, suppose [m = S m'] and that [n] is again a number such
        that [double n = double m].  We must show that [n = S m'], with
        the induction hypothesis that for every number [s], if [double s =
        double m'] then [s = m'].

        By the fact that [m = S m'] and the definition of [double], we
        have [double n = S (S (double m'))].  There are two cases to
        consider for [n].

        If [n = 0], then by definition [double n = 0], a contradiction.

        Thus, we may assume that [n = S n'] for some [n'], and again by
        the definition of [double] we have [S (S (double n')) =
        S (S (double m'))], which implies by inversion that [double n' =
        double m'].  Instantiating the induction hypothesis with [n'] thus
        allows us to conclude that [n' = m'], and it follows immediately
        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just
        what we wanted to show. [] *)

(** Before we close this section and move on to some exercises,
    let's digress briefly and use [beq_nat_true] to prove a similar
    property of identifiers that we'll need in later chapters: *)

Theorem beq_id_true : forall x y,
  beq_id x y = true -> x = y.
Proof.
  intros [m] [n]. simpl. intros H.
  assert (H' : m = n). { apply beq_nat_true. apply H. }
  rewrite H'. reflexivity.
Qed.

(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     nth_error l n = None.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a Definition
    so that we can manipulate its right-hand side.  For example, if we
    define... *)

Definition square n := n * n.

(** ... and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we get stuck: [simpl] doesn't simplify anything at this point,
    and since we haven't proved any other facts about [square], there
    is nothing we can [apply] or [rewrite] with.

    To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these facts it is not
    hard to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
  { rewrite mult_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, a deeper discussion of unfolding and simplification
    is in order.

    You may already have observed that tactics like [simpl],
    [reflexivity], and [apply] will often unfold the definitions of
    functions automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

(** then the [simpl] in the following proof (or the [reflexivity], if
    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and
    then further simplify this expression to just [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** However, this automatic unfolding is rather conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  (It is not smart enough to notice that the
    two branches of the [match] are identical.)  So it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that, itself, cannot be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone.

    At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress.

    A more straightforward way to make progress is to explicitly tell
    Coq to unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m.
  - reflexivity.
  - reflexivity.
Qed.

(* ################################################################# *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  But
    sometimes we need to reason by cases on the result of some
    _expression_.  We can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (beq_nat n 3).
    - (* beq_nat n 3 = true *) reflexivity.
    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).
      + (* beq_nat n 5 = true *) reflexivity.
      + (* beq_nat n 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat
    n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c]. *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** However, [destruct]ing compound expressions requires a bit of
    care, as such [destruct]s can sometimes erase information we need
    to complete a proof. *)
(** For example, suppose we define a function [sillyfun1] like
    this: *)

Definition sillyfun1 (n : nat) : bool :=
  if beq_nat n 3 then true
  else if beq_nat n 5 then true
  else false.

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact that [sillyfun1 n] yields [true] only when [n] is
    odd.  By analogy with the proofs we did with [sillyfun] above, it
    is natural to start the proof like this: *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3).
  (* stuck... *)
Abort.

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution performed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat n 3], but we need to keep some
    memory of this expression and how it was destructed, because we
    need to be able to reason that, since [beq_nat n 3 = true] in this
    branch of the case analysis, it must be that [n = 3], from which
    it follows that [n] is odd.

    What we would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation, giving it a
    name that we choose. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got
     stuck above, except that the context contains an extra
     equality assumption, which is exactly what we need to
     make progress. *)
    - (* e3 = true *) apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* e3 = false *)
     (* When we come to the second equality test in the body
        of the function we are reasoning about, we can use
        [eqn:] again in the same way, allow us to finish the
        proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) inversion eq.  Qed.

(** **** Exercise: 2 stars (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * Review *)

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  But basically we've got what we need to
    get work done.

    Here are the ones we've seen:

      - [intros]: move hypotheses/variables from goal to context

      - [reflexivity]: finish the proof (when the goal looks like [e =
        e])

      - [apply]: prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]: apply a hypothesis, lemma, or constructor to
        a hypothesis in the context (forward reasoning)

      - [apply... with...]: explicitly specify values for variables
        that cannot be determined by pattern matching

      - [simpl]: simplify computations in the goal

      - [simpl in H]: ... or a hypothesis

      - [rewrite]: use an equality hypothesis (or lemma) to rewrite
        the goal

      - [rewrite ... in H]: ... or a hypothesis

      - [symmetry]: changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]: changes a hypothesis of the form [t=u] into
        [u=t]

      - [unfold]: replace a defined constant by its right-hand side in
        the goal

      - [unfold... in H]: ... or a hypothesis

      - [destruct... as...]: case analysis on values of inductively
        defined types

      - [destruct... eqn:...]: specify the name of an equation to be
        added to the context, recording the result of the case
        analysis

      - [induction... as...]: induction on values of inductively
        defined types

      - [inversion]: reason by injectivity and distinctness of
        constructors

      - [assert (H: e)] (or [assert (e) as H]): introduce a "local
        lemma" [e] and call it [H]

      - [generalize dependent x]: move the variable [x] (and anything
        else that depends on it) from the context back to an explicit
        hypothesis in the goal formula *)

(* ################################################################# *)
(** * Additional Exercises *)

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

   Proof:
   (* FILL IN HERE *)
[]
*)

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We proved, in an exercise above, that for all lists of pairs,
    [combine] is the inverse of [split].  How would you formalize the
    statement that [split] is the inverse of [combine]?  When is this
    property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)

Definition split_combine_statement : Prop
  (* ("[: Prop]" means that we are giving a name to a
     logical proposition here.) *)
  (* REPLACE THIS LINE WITH   := _your_definition_ . *). Admitted.

Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.

(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:

      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (beq_nat 5) [] = true

    The second checks whether there exists an element in the list that
    satisfies a given predicate:

      existsb (beq_nat 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

      existsb evenb [] = false

    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

    Finally, prove a theorem [existsb_existsb'] stating that
    [existsb'] and [existsb] have the same behavior. *)

(* FILL IN HERE *)
(** [] *)

(** $Date: 2016-09-20 23:50:11 +0900 (2016年09月20日 (火)) $ *)


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

Inductive nat : Set :=
| O : nat
| S : nat -> nat.

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (y : natural) (lf1 : natural) : natural := plus Zero lf1.


Require Import prosa.classic.util.all.
Require Import prosa.classic.model.arrival.basic.task prosa.classic.model.arrival.basic.job prosa.classic.model.arrival.basic.task_arrival.
Require Import prosa.classic.model.schedule.global.basic.schedule.
From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.

(* Definition of response-time bound and some simple lemmas. *)
Module ResponseTime.

  Import Schedule SporadicTaskset TaskArrival.

  Section ResponseTimeBound.

    Context {sporadic_task: eqType}.
    Context {Job: eqType}.
    Variable job_arrival: Job -> time.
    Variable job_cost: Job -> time.
    Variable job_task: Job -> sporadic_task.

    (* Consider any job arrival sequence... *)
    Variable arr_seq: arrival_sequence Job.

    (* ...and any multiprocessor schedule of these jobs. *)
    Context {num_cpus : nat}.
    Variable sched: schedule Job num_cpus.

    (* For simplicity, let's define some local names.*)
    Let job_has_completed_by := completed job_cost sched.

    Section Definitions.

      (* Given a task tsk...*)
      Variable tsk: sporadic_task.

      (* ... we say that R is a response-time bound of tsk in this schedule ... *)
      Variable R: time.

      (* ... iff any job j of tsk in this arrival sequence has completed by (job_arrival j + R). *)
      Definition is_response_time_bound_of_task :=
        forall j,
          arrives_in arr_seq j ->
          job_task j = tsk ->
          job_has_completed_by j (job_arrival j + R).

    End Definitions.

    Section BasicLemmas.

      (* Assume that jobs dont execute after completion. *)
      Hypothesis H_completed_jobs_dont_execute:
        completed_jobs_dont_execute job_cost sched.

      Section SpecificJob.

        (* Then, for any job j ...*)
        Variable j: Job.
        Hypothesis H_j_arrives: arrives_in arr_seq j.

        (* ...with response-time bound R in this schedule, ... *)
        Variable R: time.
        Hypothesis response_time_bound:
          job_has_completed_by j (job_arrival j + R).

        (* ...the service received by j at any time t' after its response time is 0. *)
        Lemma service_after_job_rt_zero :
          forall t',
            t' >= job_arrival j + R ->
            service_at sched j t' = 0.
        Proof.
          rename response_time_bound into RT,
                 H_completed_jobs_dont_execute into EXEC; ins.
          unfold is_response_time_bound_of_task, completed,
                 completed_jobs_dont_execute in *.
          apply/eqP; rewrite -leqn0.
          eapply completion_monotonic in RT; eauto 2.
          apply completed_implies_not_scheduled in RT; eauto 2.
            by move: RT; rewrite not_scheduled_no_service; move => /eqP RT; rewrite RT.
        Qed.

        (* The same applies for the cumulative service of job j. *)
        Lemma cumulative_service_after_job_rt_zero :
          forall t' t'',
            t' >= job_arrival j + R ->
            \sum_(t' <= t < t'') service_at sched j t = 0.
        Proof.
          ins; apply/eqP; rewrite -leqn0.
          rewrite big_nat_cond; rewrite -> eq_bigr with (F2 := fun i => 0);
            first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.
          intro i; rewrite andbT; move => /andP [LE _].
          by rewrite service_after_job_rt_zero;
            [by ins | by apply leq_trans with (n := t')].
        Qed.

      End SpecificJob.

      Section AllJobs.

        (* Consider any task tsk ...*)
        Variable tsk: sporadic_task.

        (* ... for which a response-time bound R is known. *)
        Variable R: time.
        Hypothesis response_time_bound:
          is_response_time_bound_of_task tsk R.

        (* Then, for any job j of this task, ...*)
        Variable j: Job.
        Hypothesis H_j_arrives: arrives_in arr_seq j.
        Hypothesis H_job_of_task: job_task j = tsk.

        (* ...the service received by job j at any time t' after the response time is 0. *)
        Lemma service_after_task_rt_zero :
          forall t',
            t' >= job_arrival j + R ->
            service_at sched j t' = 0.
        Proof.
          by ins; apply service_after_job_rt_zero with (R := R); [apply response_time_bound |].
        Qed.

        (* The same applies for the cumulative service of job j. *)
        Lemma cumulative_service_after_task_rt_zero :
          forall t' t'',
            t' >= job_arrival j + R ->
            \sum_(t' <= t < t'') service_at sched j t = 0.
        Proof.
          by ins; apply cumulative_service_after_job_rt_zero with (R := R);
            first by apply response_time_bound.
        Qed.

      End AllJobs.

    End BasicLemmas.

  End ResponseTimeBound.

End ResponseTime.