(**
CoLoR, a Coq library on rewriting and termination.
See the COPYRIGHTS and LICENSE files.

- Frederic Blanqui, 2005-06-10

signature for algebraic terms with no arity
*)

Set Implicit Arguments.

From CoLoR Require Import LogicUtil.

(***********************************************************************)
(** Variables are represented by natural numbers. *)

Notation variable := nat (only parsing).

(***********************************************************************)
(** Signature with a decidable set of symbols of fixed arity. *)

Record Signature : Type := mkSignature {
  symbol :> Type;
  beq_symb : symbol -> symbol -> bool;
  beq_symb_ok : forall x y, beq_symb x y = true <-> x = y
}.

Arguments mkSignature [symbol beq_symb] _.
Arguments beq_symb [s] _ _.
Arguments beq_symb_ok {s x y}.

From CoLoR Require Import EqUtil.

Ltac case_beq_symb Sig := EqUtil.case_beq (@beq_symb Sig) (@beq_symb_ok Sig).

Definition eq_symb_dec Sig := dec_beq (@beq_symb_ok Sig).

Arguments eq_symb_dec [Sig] _ _.

(***********************************************************************)
(** Tactic for proving beq_symb_ok *)

Ltac beq_symb_ok := intros f g; split;
  [destruct f; destruct g; simpl; intro; (discr || refl)
    | intro; subst g; destruct f; refl].

(***********************************************************************)
(** Modules and module types for signatures *)

Module Type SIG.
  Parameter Sig : Signature.
End SIG.

(* DecidableType *)
From Coq Require Import DecidableType.
Module DecType (Import S : SIG) <: DecidableType.
  Definition t := @symbol Sig.
  Definition eq := @eq t.
  Definition eq_refl := @eq_refl t.
  Definition eq_sym := @eq_sym t.
  Definition eq_trans := @eq_trans t.
  Definition eq_dec := EqUtil.dec_beq (@beq_symb_ok Sig).
End DecType.

(* finite signature *)
From CoLoR Require Import ListUtil.
Module Type FSIG.
  Parameter Sig : Signature.
  Parameter Fs : list Sig.
  Parameter Fs_ok : forall f, In f Fs.
End FSIG.

(***********************************************************************)
(** Weighted signatures *)

Module Type WSIG.
  Parameter Sig : Signature.
  Parameter weight : Sig -> nat.
  Parameter weight_inj : forall f g, weight f = weight g -> f = g.
End WSIG.

From CoLoR Require Import NatUtil BoolUtil.

Section weight_inj.

  Variable Sig : Signature.
  Variable Fs : list Sig.
  Variable Fs_ok : forall f, In f Fs.
  Variable weight : Sig -> nat.

  Definition bweight_inj :=
    forallb (fun f => forallb (fun g =>
      implb (beq_nat (weight f) (weight g)) (beq_symb f g)) Fs) Fs.

  Lemma bweight_inj_ok : bweight_inj = true <->
    (forall f g, weight f = weight g -> f = g).

  Proof.
    unfold bweight_inj. apply forallb_ok_fintype. 2: hyp. intro f.
    apply forallb_ok_fintype. 2: hyp. intro g. unfold implb.
    case_eq (beq_nat (weight f) (weight g)).
    rewrite beq_nat_ok, beq_symb_ok. tauto.
    rewrite (beq_ko beq_nat_ok). tauto.
  Qed.

End weight_inj.

(*Arguments bweight_inj_ok _ [Fs] _ [weight].*)

Ltac weight_inj Fs_ok := rewrite <- (bweight_inj_ok _ Fs_ok);
  (check_eq || fail 10 "non-injective weight function").

(***********************************************************************)
(** Ordered signatures *)

From Coq Require Import OrderedType.

Module OrdType (Import S : WSIG) <: OrderedType.

  Include (DecType S).

  Definition lt f g := weight f < weight g.

  Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.

  Proof. unfold lt. intros. lia. Qed.

  Lemma lt_not_eq : forall x y, lt x y -> x <> y.

  Proof. unfold lt. intros x y l e. subst. lia. Qed.

  Definition blt f g := bgt_nat (weight g) (weight f).

  Lemma blt_ok : forall f g, blt f g = true <-> lt f g.

  Proof. intros f g. unfold blt, lt. apply bgt_nat_ok. Qed.

  Lemma lt_total : forall f g,
    beq_symb f g = false -> blt f g = false -> blt g f = true.

  Proof.
    intros f g. unfold blt.
    rewrite bgt_nat_ok, bgt_nat_ko, (beq_ko (@beq_symb_ok Sig)). intros.
    destruct (eq_nat_dec (weight f) (weight g)).
    ded (weight_inj e). subst g. cong.
    lia.
  Qed.

  Definition compare : forall x y, Compare lt (@Logic.eq t) x y.

  Proof.
    intros x y. case_eq (beq_symb x y); intro H.
    rewrite beq_symb_ok in H. apply (EQ H).
    case_eq (blt x y); intro H0.
    rewrite blt_ok in H0. apply (LT H0).
    eapply GT. rewrite <- blt_ok. apply lt_total; hyp.
  Defined.

End OrdType.


(* -*- compile-command: "cd .. && ./makedoc.sh" -*- *)
(* begin hide *)
Require Import Omega FingerTree.Modules.
Require Import FingerTree.DependentFingerTreeModule.
Require Import Coq.Program.Program Coq.Program.Equality.
Require JMeq.
Require Coq.Program.Equality.
Implicit Type v A : Type.
Unset Standard Proposition Elimination Names.

Set Implicit Arguments.
(* end hide *)
(** printing lparr $\coqdoublebar$ *)(** printing rparr $\coqdoublebar$ *)(** printing cdot $\cdot$ *)(** printing epsilon $\varepsilon$ *)(** printing +:+ $\treeapp$ *)(** printing ++ $\app$ *)(** printing := $\coloneqq$ *)(** printing :> $\Yright$ *)(** printing < $<$ *)(** printing > $>$ *)
(** ** FingerTree: a non-dependent interface

   As shown before, we can wrap the measure and the tree in a dependent pair to offer a simpler
   interface to Finger Trees.
   %\def\coqdocindent#1{\noindent\kern#1}%
   *)

Module FingerTree(M : Monoid) (Ms : Measured with Module Mon := M).
  Import M.
  Import Ms.
  Module FT := DependentFingerTree M.
  Import FT.
  Definition v := M.m.

  Definition finger_tree :=
    { m : v & fingertree measure m }.

  Notation " ts :| t " := (existT _ ts t) (at level 20).

  (** This gives us a type [finger_tree v mono A measure], which can be compared with
     the original [finger_tree v a] datatype in Haskell. It adds the [monoid] implementation
     and [measure] function as explicit parameters whereas in Haskell they are passed implicitely
     using the typeclass mechanism. Morally, the parameterization we did using the section
     mechanism correspond to the systematic prefixing of functions on [FingerTree] objects by a
     [Measured v a] constraint in Haskell ([Measured v a] is a class with a single function
     [measure] of type [a -> v] where [v] must have a [Monoid] instance). We
     think this equivalence indicates an interesting field of investigations
     on how to integrate overloading in a language like Russell, or a section system in Haskell.
     *)
  (* begin hide *)
  (** Now we can wrap all the operations on [fingertree] objects. *)
  Program Definition empty : finger_tree := epsilon :| Empty.

  Program Definition is_empty (s : finger_tree) : Prop :=
    let 'ts :| t := s in isEmpty t.

  Program Definition is_empty_dec (s : finger_tree)
    : {is_empty s} + {~is_empty s} :=
    let 'ts :| t := s in
    if isEmpty_dec t then left _ else right _.

  Program Definition singleton (x : A) : finger_tree :=
    _ :| Single x.

  Program Definition cons (x : A) (s : finger_tree) : finger_tree :=
    let 'ts :| t := s in _ :| add_left x t.

  Program Definition snoc (s : finger_tree) (x : A) : finger_tree :=
    let '_ :| t := s in _ :| add_right t x.

  Program Definition head (s : finger_tree | ~ is_empty s) : A :=
    let '_ :| t := s in head t.

  Program Definition last (s : finger_tree | ~ is_empty s) : A :=
    let '_ :| t := s in last t.

  Program Definition tail (s : finger_tree | ~ is_empty s) : finger_tree :=
    let '_ :| t := s in tail t.

  Program Definition liat (s : finger_tree | ~ is_empty s) : finger_tree :=
    let '_ :| t := s in liat t.

  Definition tree_measure (s : finger_tree) : v :=
    let 'ts :| _ := s in ts.

  Import JMeq.

  Program Definition tree_size (s : finger_tree) : nat :=
    let '_ :| t := s in tree_size t.

  (* end hide *)
  (**
     We do not describe the wrapping in detail, it is just destructuring a [finger_tree] object,
     calling the appropriate function on [fingertree]s and packing back the measure and the tree.
     However, an important point is that we can wrap views too
     and obviously recover the associated measure: *)

  Inductive left_view : Type :=
  | nil_left : left_view | cons_left : A -> finger_tree -> left_view.
  (* begin hide *)
  Program Definition view_left (s : finger_tree) : left_view :=
    let '_ :| t := s in
    match view_L t with
      | nil_L => nil_left
      | cons_L x ts t => cons_left x (ts :| t)
    end.
  (* end hide *)

  Lemma view_left_size : forall t x t', view_left t = cons_left x t' ->
    tree_size t' < tree_size t.
  Proof.
    intros.
    destruct t ; destruct t' ; simpl in *.
    generalize H ; clear H.
    remember (view_L f) as vf.
    destruct vf ; simpl in * ; intros ; try discriminate.
    symmetry in Heqvf.
    pose (view_L_size_measure f Heqvf).
    inversion H.
    subst.
    assert(Hi:=inj_pair2 H3).
    subst f0.
    simpl.
    omega.
  Qed.
  (* begin hide *)
  Inductive right_view : Type :=
  | nil_right : right_view
  | cons_right : finger_tree -> A -> right_view.

  Program Definition view_right (s : finger_tree) : right_view :=
    let '_ :| t := s in
    match view_R t with
      | nil_R => nil_right
      | cons_R ts t x => cons_right (ts :| t) x
    end.

  Lemma view_right_size : forall t t' x, view_right t = cons_right t' x -> tree_size t > tree_size t'.
  Proof.
    intros.
    destruct t ; destruct t' ; simpl in *.
    generalize H ; clear H.
    remember (view_R f) as vf.
    destruct vf ; simpl in * ; intros ; try discriminate.
    symmetry in Heqvf.
    (*pose (view_R_size_measure f Heqvf).
    inversion H.
    simpl.
    omega.*)
  Admitted.

  (** We wrap concatenation using a simple type but we export the split invariants in an inductive. *)

  Program Definition cat (s s' : finger_tree) : finger_tree :=
    let 's :| ss := s in
    let 'ts' :| ss' := s' in
      _ :| app ss ss'.

  Obligation Tactic := program_simpl.

  Section Splits.

    Program Definition get (p : v -> bool) (x : finger_tree | ~ is_empty x)
      (i : v | p i = false /\ p (i cdot tree_measure x) = true) : v * A :=
      let 's :| t := x in
        get_tree p t tt i.

  (**
     The [Split] inductive is is a direct wrapper of the [tree_split] datatype. *)

    Inductive Split (p : v -> bool) (i : v) : Type :=
    mkSplit : forall (l : { l : finger_tree | is_empty l \/
      p (i cdot tree_measure l) = false }) (x : A) (r : finger_tree | is_empty r \/
      p (i cdot tree_measure (`l) cdot measure x) = true), Split p i.

    (** Correspondingly, the function [split] just wraps the original [split_tree] definition. *)

    Program Definition split (p : v -> bool)(i : v) (x : finger_tree | ~ is_empty x)
      : Split p i :=
      let 's :| t := x in
      let 'mkTreeSplit ls l x rs r := split_tree p i t in
        mkSplit p i (ls :| `l) x (rs :| `r).

  (* end hide *)

    (** %\def\coqdocindent#1{\noindent\kern#1\hskip-1em}\label{def:split_with}%We can finally wrap splitting
       on [finger_tree]s along a predicate. We offer the same
       simply-typed interface as Haskell by definining the function [split_with p x].
       It splits any tree [x] by first checking if [x] is empty and if
       not calls the [split] function on it using the predicate [p] with an empty accumulator.
       %\extended{Its first and second projections give the [takeUntil] and [dropUntil] functions
       which return respectively the prefix of the tree for which the predicate was [false]
       and the rest of the tree.}% *)

    Program Definition split_with (p : v -> bool)
      (x : finger_tree) : finger_tree * finger_tree :=
      if is_empty_dec x then (empty, empty)
      else let (l, x, r) := split p epsilon x in (l, cons x r).

    (* begin hide *)
    Program Definition takeUntil (p : v -> bool) (x : finger_tree) : finger_tree :=
      fst (split_with p x).

    Program Definition dropUntil (p : v -> bool) (x : finger_tree) : finger_tree :=
      snd (split_with p x).

    Program Definition size_split (x : finger_tree * finger_tree) : nat :=
      let (x,y) := x in tree_size x + tree_size y.

    Import Coq.Program.Equality.

    Print mkTreeSplit.

(*     Program Definition coerce_tree_split_v (v : Type) (mono : monoid v) (p : v -> bool)  *)
(*       (A : Type) (measure : A -> v) (i : v) (s : v) (t : tree_split mono p measure i s) *)
(*       (s' : v) (H : s = s') : tree_split mono p measure i s' := *)
(*       match t in tree_split _ _ _ _ s return s = s' -> tree_split mono p measure i s' with *)
(*         mkTreeSplit xsm xs x ysm ys => fun H => mkTreeSplit p i xs x ys *)
(*       end H. *)

(*     Lemma cut_tree_split : forall (v : Type) (mono : monoid v) (p : v -> bool)  *)
(*       (A : Type) (measure : A -> v) (i : v) (s : v) *)
(*       (P :  *)
(*         forall xsm, *)
(*           forall {xs : fingertree mono measure xsm | *)
(*             isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*           forall (x : A) (ysm : v), *)
(*             forall {ys : fingertree mono measure ysm | *)
(*               isEmpty ys \/ *)
(*                 p *)
(*                 (Monoid.mappend mono i *)
(*                   (Monoid.mappend mono xsm (measure x))) = true}, *)

(*             tree_split mono p measure i (Monoid.mappend mono xsm (Monoid.mappend mono (measure x) ysm)) ->  *)
(*             Type), *)
(*       forall xsm, *)
(*         forall {xs : fingertree mono measure xsm | *)
(*           isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*         forall (x : A) (ysm : v), *)
(*           forall {ys : fingertree mono measure ysm | *)
(*             isEmpty ys \/ *)
(*             p *)
(*             (Monoid.mappend mono i *)
(*               (Monoid.mappend mono xsm (measure x))) = true}, *)
(*       forall  *)

(*         (b :       forall xsm, *)
(*         forall {xs : fingertree mono measure xsm | *)
(*           isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*         forall (x : A) (ysm : v), *)
(*           forall {ys : fingertree mono measure ysm | *)
(*             isEmpty ys \/ *)
(*             p *)
(*             (Monoid.mappend mono i *)
(*               (Monoid.mappend mono xsm (measure x))) = true}, P xsm xs x ysm ys (mkTreeSplit p i xs x ys)) *)
(*         , *)

(*       forall s' (H : (Monoid.mappend mono xsm (Monoid.mappend mono (measure x) ysm)) = s'), *)

(*             match *)
(*               eq_rect (fun s : v => tree_split mono p measure i s) *)
(*               (mkTreeSplit p i xs x ys) s' H as x0 in (tree_split _ _ _ _ v0) *)
(*                 return P x0 *)
(*               with mkTreeSplit xsm xs x ysm ys =>  *)
(*                 b xsm xs x ysm ys *)
(*             end. *)

    Lemma split_size : forall (p : v -> bool) (t : finger_tree) s,
      split_with p t = s -> tree_size t = size_split s.
    Proof.
      intros.
      induction t.
      unfold split_with.
      unfold split_with in H.
      destruct (is_empty_dec (x :| p0)) ; simpl in * ; auto.
      subst s.
      unfold tree_size.
      simpl ; auto.
      assert (He:=isEmpty_epsilon _ i) ; subst x.
      assert (He:=isEmpty_Empty p0 i).
      subst p0 ; simpl ; auto.

      subst s.
      destruct p0.
      unfold isEmpty in n ; simpl in n.
      elim n ;  auto.

    Admitted.

(*       unfold split ; simpl. *)
(*       unfold split_tree ; simpl. *)
(*       on_coerce_proof_gl ltac:(fun p => set(H:=p)). *)

(*       Set Printing Implicit. *)
(*       Unset Printing Notations. *)
(*       intros. *)
(*       match goal with *)
(*         | |- ?T =>  *)

(*       pattern H. *)
(*       generalize dependent H. *)
(*       pattern (mappend mempty (mappend (measure x) mempty)) at 1 2. *)

(*       generalize *)
(*       (eq_rect (epsilon cdot measure x cdot epsilon) *)
(*               (fun H0 : Digits.v => tree_split p measure epsilon H0) *)
(*               (mkTreeSplit p epsilon (Empty )%subset x (Empty &?)%subset) *)
(*               (measure x) H). *)
(*       generalize dependent H. *)
(*       rewrite H in H. *)
(*       clearbody H. *)
(*     Admitted. *)

  End Splits.
  (* end hide *)
End FingerTree.


Set Warnings "-notation-overridden".

Require Import Category.Lib.
Require Export Category.Theory.Functor.

Generalizable All Variables.
Set Primitive Projections.
Set Universe Polymorphism.
Unset Transparent Obligations.

Inductive TwoObj : Type := TwoX | TwoY.

Inductive TwoHom : TwoObj -> TwoObj -> Type :=
  | TwoIdX : TwoHom TwoX TwoX
  | TwoIdY : TwoHom TwoY TwoY
  | TwoXY  : TwoHom TwoX TwoY.

Definition TwoHom_inv_t : forall x y, TwoHom x y -> Prop.
Proof.
  intros [] [] f.
  exact (f = TwoIdX).
  exact (f = TwoXY).
  exact False.          (* Unused, any Prop is ok here *)
  exact (f = TwoIdY).
Defined.

Corollary TwoHom_inv x y f : TwoHom_inv_t x y f.
Proof. destruct f; reflexivity. Qed.

Lemma TwoHom_Y_X_absurd : TwoHom TwoY TwoX -> False.
Proof. inversion 1. Qed.

Hint Extern 4 => contradiction TwoHom_Y_X_absurd : two_laws.

(* The category 2 has two objects, their identity morphisms, and one morphism
   from the first object to the second (here denoted false and true). *)

Program Definition _2 : Category := {|
  obj     := TwoObj;
  hom     := TwoHom;
  homset  := Morphism_equality;
  id      := fun x => match x with
    | TwoX => TwoIdX
    | TwoY => TwoIdY
    end;
  compose := fun x y z (f : TwoHom y z) (g : TwoHom x y) =>
    match x, y, z with
    | TwoX, TwoX, TwoX => TwoIdX
    | TwoY, TwoY, TwoY => TwoIdY
    | TwoX, TwoX, TwoY => TwoXY
    | TwoX, TwoY, TwoY => TwoXY
    | _,    _,    _    => _
    end
|}.
Next Obligation. destruct x, y, z; intuition. Qed.
Next Obligation.
  destruct x, y, z; auto with two_laws;
  intuition; discriminate.
Qed.
Next Obligation.
  destruct x, y, z; auto with two_laws;
  intuition; discriminate.
Qed.
Next Obligation.
  destruct x, y, z; auto with two_laws;
  intuition; discriminate.
Qed.
Next Obligation.
  destruct x, y; auto with two_laws; intuition;
  symmetry; exact (TwoHom_inv _ _ f).
Qed.
Next Obligation.
  destruct x, y; auto with two_laws; intuition;
  symmetry; exact (TwoHom_inv _ _ f).
Qed.
Next Obligation.
  destruct x, y, z, w; auto with two_laws; intuition.
Qed.
Next Obligation.
  destruct x, y, z, w; auto with two_laws; intuition.
Qed.


(* *********************************************************************)
(*                                                                     *)
(*              The Compcert verified compiler                         *)
(*                                                                     *)
(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)
(*                                                                     *)
(*  Copyright Institut National de Recherche en Informatique et en     *)
(*  Automatique.  All rights reserved.  This file is distributed       *)
(*  under the terms of the GNU General Public License as published by  *)
(*  the Free Software Foundation, either version 2 of the License, or  *)
(*  (at your option) any later version.  This file is also distributed *)
(*  under the terms of the INRIA Non-Commercial License Agreement.     *)
(*                                                                     *)
(* *********************************************************************)

(** Definitions and theorems about semi-open integer intervals *)

Require Import Coqlib.
Require Import Zwf.
Require Coq.Program.Wf.
Require Import Recdef.

Definition interv : Type := (Z * Z)%type.

(** * Membership *)

Definition In (x: Z) (i: interv) : Prop := fst i <= x < snd i.

Lemma In_dec:
  forall x i, {In x i} + {~In x i}.
Proof.
  unfold In; intros.
  case (zle (fst i) x); intros.
  case (zlt x (snd i)); intros.
  left; auto.
  right; intuition.
  right; intuition.
Qed.

Lemma notin_range:
  forall x i,
  x < fst i \/ x >= snd i -> ~In x i.
Proof.
  unfold In; intros; lia.
Qed.

Lemma range_notin:
  forall x i,
  ~In x i -> fst i < snd i -> x < fst i \/ x >= snd i.
Proof.
  unfold In; intros; lia.
Qed.

(** * Emptyness *)

Definition empty (i: interv) : Prop := fst i >= snd i.

Lemma empty_dec:
  forall i, {empty i} + {~empty i}.
Proof.
  unfold empty; intros.
  case (zle (snd i) (fst i)); intros.
  left; lia.
  right; lia.
Qed.

Lemma is_notempty:
  forall i, fst i < snd i -> ~empty i.
Proof.
  unfold empty; intros; lia.
Qed.

Lemma empty_notin:
  forall x i, empty i -> ~In x i.
Proof.
  unfold empty, In; intros. lia.
Qed.

Lemma in_notempty:
  forall x i, In x i -> ~empty i.
Proof.
  unfold empty, In; intros. lia.
Qed.

(** * Disjointness *)

Definition disjoint (i j: interv) : Prop :=
  forall x, In x i -> ~In x j.

Lemma disjoint_sym:
  forall i j, disjoint i j -> disjoint j i.
Proof.
  unfold disjoint; intros; red; intros. elim (H x); auto.
Qed.

Lemma empty_disjoint_r:
  forall i j, empty j -> disjoint i j.
Proof.
  unfold disjoint; intros. apply empty_notin; auto.
Qed.

Lemma empty_disjoint_l:
  forall i j, empty i -> disjoint i j.
Proof.
  intros. apply disjoint_sym. apply empty_disjoint_r; auto.
Qed.

Lemma disjoint_range:
  forall i j,
  snd i <= fst j \/ snd j <= fst i -> disjoint i j.
Proof.
  unfold disjoint, In; intros. lia.
Qed.

Lemma range_disjoint:
  forall i j,
  disjoint i j ->
  empty i \/ empty j \/ snd i <= fst j \/ snd j <= fst i.
Proof.
  unfold disjoint, empty; intros.
  destruct (zlt (fst i) (snd i)); auto.
  destruct (zlt (fst j) (snd j)); auto.
  right; right.
  destruct (zlt (fst i) (fst j)).
(* Case 1: i starts to the left of j. *)
  destruct (zle (snd i) (fst j)).
(* Case 1.1: i ends to the left of j, OK *)
  auto.
(* Case 1.2: i ends to the right of j's start, not disjoint. *)
  elim (H (fst j)). red; lia. red; lia.
(* Case 2: j starts to the left of i *)
  destruct (zle (snd j) (fst i)).
(* Case 2.1: j ends to the left of i, OK *)
  auto.
(* Case 2.2: j ends to the right of i's start, not disjoint. *)
  elim (H (fst i)). red; lia. red; lia.
Qed.

Lemma range_disjoint':
  forall i j,
  disjoint i j -> fst i < snd i -> fst j < snd j ->
  snd i <= fst j \/ snd j <= fst i.
Proof.
  intros. exploit range_disjoint; eauto. unfold empty; intuition lia.
Qed.

Lemma disjoint_dec:
  forall i j, {disjoint i j} + {~disjoint i j}.
Proof.
  intros.
  destruct (empty_dec i). left; apply empty_disjoint_l; auto.
  destruct (empty_dec j). left; apply empty_disjoint_r; auto.
  destruct (zle (snd i) (fst j)). left; apply disjoint_range; auto.
  destruct (zle (snd j) (fst i)). left; apply disjoint_range; auto.
  right; red; intro. exploit range_disjoint; eauto. intuition.
Qed.

(** * Shifting an interval by some amount *)

Definition shift (i: interv) (delta: Z) : interv := (fst i + delta, snd i + delta).

Lemma in_shift:
  forall x i delta,
  In x i -> In (x + delta) (shift i delta).
Proof.
  unfold shift, In; intros. simpl. lia.
Qed.

Lemma in_shift_inv:
  forall x i delta,
  In x (shift i delta) -> In (x - delta) i.
Proof.
  unfold shift, In; simpl; intros. lia.
Qed.

(** * Enumerating the elements of an interval *)

Section ELEMENTS.

Variable lo: Z.

Function elements_rec (hi: Z) {wf (Zwf lo) hi} : list Z :=
  if zlt lo hi then (hi-1) :: elements_rec (hi-1) else nil.
Proof.
  intros. red. lia.
  apply Zwf_well_founded.
Qed.

Lemma In_elements_rec:
  forall hi x,
  List.In x (elements_rec hi) <-> lo <= x < hi.
Proof.
  intros. functional induction (elements_rec hi).
  simpl; split; intros.
  destruct H. clear IHl. lia. rewrite IHl in H. clear IHl. lia.
  destruct (zeq (hi - 1) x); auto. right. rewrite IHl. clear IHl. lia.
  simpl; intuition.
Qed.

End ELEMENTS.

Definition elements (i: interv) : list Z :=
  elements_rec (fst i) (snd i).

Lemma in_elements:
  forall x i,
  In x i -> List.In x (elements i).
Proof.
  intros. unfold elements. rewrite In_elements_rec. auto.
Qed.

Lemma elements_in:
  forall x i,
  List.In x (elements i) -> In x i.
Proof.
  unfold elements; intros.
  rewrite In_elements_rec in H. auto.
Qed.

(** * Checking properties on all elements of an interval *)

Section FORALL.

Variables P Q: Z -> Prop.
Variable f: forall (x: Z), {P x} + {Q x}.
Variable lo: Z.

Program Fixpoint forall_rec (hi: Z) {wf (Zwf lo) hi}:
                 {forall x, lo <= x < hi -> P x}
                 + {exists x, lo <= x < hi /\ Q x} :=
  if zlt lo hi then
    match f (hi - 1) with
    | left _ =>
        match forall_rec (hi - 1) with
        | left _ => left _ _
        | right _ => right _ _
        end
    | right _ => right _ _
    end
  else
    left _ _
.
Next Obligation.
  red. lia.
Qed.
Next Obligation.
  assert (x = hi - 1 \/ x < hi - 1) by lia.
  destruct H2. congruence. auto.
Qed.
Next Obligation.
  exists wildcard'; split; auto. lia.
Qed.
Next Obligation.
  exists (hi - 1); split; auto. lia.
Qed.
Next Obligation.
  extlia.
Defined.

End FORALL.

Definition forall_dec
       (P Q: Z -> Prop) (f: forall (x: Z), {P x} + {Q x}) (i: interv) :
       {forall x, In x i -> P x} + {exists x, In x i /\ Q x} :=
 forall_rec P Q f (fst i) (snd i).

(** * Folding a function over all elements of an interval *)

Section FOLD.

Variable A: Type.
Variable f: Z -> A -> A.
Variable lo: Z.
Variable a: A.

Function fold_rec (hi: Z) {wf (Zwf lo) hi} : A :=
  if zlt lo hi then f (hi - 1) (fold_rec (hi - 1)) else a.
Proof.
  intros. red. lia.
  apply Zwf_well_founded.
Qed.

Lemma fold_rec_elements:
  forall hi, fold_rec hi = List.fold_right f a (elements_rec lo hi).
Proof.
  intros. functional induction (fold_rec hi).
  rewrite elements_rec_equation. rewrite zlt_true; auto.
  simpl. congruence.
  rewrite elements_rec_equation. rewrite zlt_false; auto.
Qed.

End FOLD.

Definition fold {A: Type} (f: Z -> A -> A) (a: A) (i: interv) : A :=
  fold_rec A f (fst i) a (snd i).

Lemma fold_elements:
  forall (A: Type) (f: Z -> A -> A) a i,
  fold f a i = List.fold_right f a (elements i).
Proof.
  intros. unfold fold, elements. apply fold_rec_elements.
Qed.

(** Hints *)

Hint Resolve
  notin_range range_notin
  is_notempty empty_notin in_notempty
  disjoint_sym empty_disjoint_r empty_disjoint_l
  disjoint_range
  in_shift in_shift_inv
  in_elements elements_in : intv.


Theorem ex_mid_iff_d_neg: forall P:Prop, ~P\/P<->(P<->~~P).
Proof. intros. split.
       - intros. split. destruct H. intros. unfold not. intros. apply H1. apply H0.
         intros. unfold not. intros. apply H1. apply H. destruct H. unfold not in H.
         unfold not. intros. assert (False). { apply H0. apply H. } inversion H1.
         unfold not. intros. apply H.
       - unfold not. intros. destruct H.


(* This program is free software; you can redistribute it and/or      *)
(* modify it under the terms of the GNU Lesser General Public License *)
(* as published by the Free Software Foundation; either version 2.1   *)
(* of the License, or (at your option) any later version.             *)
(*                                                                    *)
(* This program is distributed in the hope that it will be useful,    *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)
(* GNU General Public License for more details.                       *)
(*                                                                    *)
(* You should have received a copy of the GNU Lesser General Public   *)
(* License along with this program; if not, write to the Free         *)
(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)
(* 02110-1301 USA                                                     *)

Set Implicit Arguments.
Unset Strict Implicit.
Require Export Sub_monoid.
Require Export Group_facts.
Section Def.
Variable G : GROUP.
Section Sub_group.
Variable H : submonoid G.
Hypothesis Hinv : forall x : G, in_part x H -> in_part (group_inverse _ x) H.

Definition subgroup_inv : MAP H H.
apply
 (Build_Map (A:=H) (B:=H)
    (Ap:=fun x : H => Build_subtype (Hinv (subtype_prf x)))).
red in |- *.
simpl in |- *.
unfold subtype_image_equal in |- *.
simpl in |- *.
auto with algebra.
Defined.

Definition subgroup_group : group.
apply (Build_group (group_monoid:=H)).
apply (Build_group_on (G:=H) (group_inverse_map:=subgroup_inv)).
red in |- *.
simpl in |- *.
unfold subtype_image_equal in |- *.
simpl in |- *.
auto with algebra.
red in |- *.
simpl in |- *.
unfold subtype_image_equal in |- *.
simpl in |- *.
auto with algebra.
Defined.
End Sub_group.

Record subgroup : Type :=
  {subgroup_submonoid : submonoid G;
   subgroup_prop :
    forall x : G,
    in_part x subgroup_submonoid ->
    in_part (group_inverse _ x) subgroup_submonoid}.

Definition group_of_subgroup (H : subgroup) :=
  subgroup_group (subgroup_prop (s:=H)).
End Def.
Coercion group_of_subgroup : subgroup >-> group.
Coercion subgroup_submonoid : subgroup >-> submonoid.
Section Injection.
Variable G : GROUP.
Variable H : subgroup G.

Lemma subgroup_in_prop :
 forall x : G, in_part x H -> in_part (group_inverse _ x) H.
intros x H'; try assumption.
apply (subgroup_prop (G:=G) (s:=H)); auto with algebra.
Qed.

Definition inj_subgroup : Hom (H:GROUP) G.
apply (Build_monoid_hom (E:=H) (F:=G) (monoid_sgroup_hom:=inj_subsgroup H)).
red in |- *.
auto with algebra.
Defined.

Lemma inj_subgroup_injective : injective inj_subgroup.
red in |- *.
auto with algebra.
Qed.
End Injection.
Hint Resolve subgroup_in_prop inj_subgroup_injective: algebra.


(*
MacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop
Welcome to Coq 8.4pl5 (October 2014)

Coq < Section Addition_C.

Coq < Goal forall w z a m o:Prop, (w <-> z) -> ((w <-> z) \/ (a -> (m -> o))).
1 subgoal

  ============================
   forall w z a m o : Prop, (w <-> z) -> (w <-> z) \/ (a -> m -> o)

Unnamed_thm < intros.
1 subgoal

  w : Prop
  z : Prop
  a : Prop
  m : Prop
  o : Prop
  H : w <-> z
  ============================
   (w <-> z) \/ (a -> m -> o)

Unnamed_thm < left.
1 subgoal

  w : Prop
  z : Prop
  a : Prop
  m : Prop
  o : Prop
  H : w <-> z
  ============================
   w <-> z

Unnamed_thm < exact H.
No more subgoals.

Unnamed_thm < Qed.
intros.
left.
exact H.

Unnamed_thm is defined

Coq <

*)

Section Addition_C.
Goal forall w z a m o:Prop, (w <-> z) -> ((w <-> z) \/ (a -> (m -> o))).
intros.
left.
exact H.
Qed.


Require Export prosa.model.schedule.work_conserving.
Require Export prosa.analysis.definitions.job_properties.
Require Export prosa.analysis.definitions.priority_inversion.
Require Export prosa.analysis.facts.behavior.all.
Require Export prosa.analysis.facts.model.service_of_jobs.

(** Throughout this file, we assume ideal uni-processor schedules. *)
Require Import prosa.model.processor.ideal.

(** Throughout this file, we assume the basic (i.e., Liu & Layland) readiness model. *)
Require Import prosa.model.readiness.basic.

(** * Existence of Busy Interval for JLFP-models *)
(** In this module we derive a sufficient condition for existence of
    busy intervals for uni-processor for JLFP schedulers. *)
Section ExistsBusyIntervalJLFP.

  (** Consider any type of tasks ... *)
  Context {Task : TaskType}.
  Context `{TaskCost Task}.

  (**  ... and any type of jobs associated with these tasks. *)
  Context {Job : JobType}.
  Context `{JobTask Job Task}.
  Context `{JobArrival Job}.
  Context `{JobCost Job}.

  (** Consider any arrival sequence with consistent arrivals. *)
  Variable arr_seq : arrival_sequence Job.
  Hypothesis H_arrival_times_are_consistent : consistent_arrival_times arr_seq.

  (** Next, consider any ideal uni-processor schedule of this arrival sequence ... *)
  Variable sched : schedule (ideal.processor_state Job).
  Hypothesis H_jobs_come_from_arrival_sequence:
    jobs_come_from_arrival_sequence sched arr_seq.

  (** ... where jobs do not execute before their arrival or after completion. *)
  Hypothesis H_jobs_must_arrive_to_execute : jobs_must_arrive_to_execute sched.
  Hypothesis H_completed_jobs_dont_execute : completed_jobs_dont_execute sched.

  (** Assume a given JLFP policy. *)
  Context `{JLFP_policy Job}.

  (** For simplicity, let's define some local names. *)
  Let job_pending_at := pending sched.
  Let job_completed_by := completed_by sched.
  Let arrivals_between := arrivals_between arr_seq.

  (** Consider an arbitrary task [tsk]. *)
  Variable tsk : Task.

  (** Consider an arbitrary job [j]. *)
  Variable j : Job.
  Hypothesis H_from_arrival_sequence : arrives_in arr_seq j.
  Hypothesis H_job_task : job_of_task tsk j.
  Hypothesis H_job_cost_positive : job_cost_positive j.

  (** Recall the list of jobs that arrive in any interval. *)
  Let quiet_time t1 := quiet_time arr_seq sched j t1.
  Let quiet_time_dec t1 := quiet_time_dec arr_seq sched j t1.
  Let busy_interval_prefix t1 t2 := busy_interval_prefix arr_seq sched j t1 t2.
  Let busy_interval t1 t2 := busy_interval arr_seq sched j t1 t2.
  Let is_priority_inversion_bounded_by K := priority_inversion_of_job_is_bounded_by arr_seq sched j K.

  (** We begin by proving a basic lemma about completion of the job within its busy interval. *)
  Section BasicLemma.

    (** Assume that the priority relation is reflexive. *)
    Hypothesis H_priority_is_reflexive : reflexive_priorities.

    (** Consider any busy interval <<[t1, t2)>> of job [j]. *)
    Variable t1 t2 : instant.
    Hypothesis H_busy_interval : busy_interval t1 t2.

    (** We prove that job j completes by the end of the busy interval. *)
    Lemma job_completes_within_busy_interval:
      job_completed_by j t2.
    Proof.
      rename H_priority_is_reflexive into REFL, H_busy_interval into BUSY.
      move: BUSY => [[_ [_ [_ /andP [_ ARR]]]] QUIET].
      apply QUIET; try done.
      apply (REFL 0).
    Qed.

  End BasicLemma.

  (** In this section, we prove that during a busy interval there
         always exists a pending job. *)
  Section ExistsPendingJob.

    (** Let [[t1, t2]] be any interval where time t1 is quiet and time t2 is not quiet. *)
    Variable t1 t2 : instant.
    Hypothesis H_interval : t1 <= t2.
    Hypothesis H_quiet : quiet_time t1.
    Hypothesis H_not_quiet : ~ quiet_time t2.

    (** Then, we prove that there is a job pending at time t2
         that has higher or equal priority (with respect of [tsk]). *)
    Lemma not_quiet_implies_exists_pending_job:
      exists j_hp,
        arrives_in arr_seq j_hp /\
        arrived_between j_hp t1 t2 /\
        hep_job j_hp j /\
        ~ job_completed_by j_hp t2.
    Proof.
      rename H_quiet into QUIET, H_not_quiet into NOTQUIET.
      destruct (has (fun j_hp => (~~ job_completed_by j_hp t2) && hep_job j_hp j)
                    (arrivals_between t1 t2)) eqn:COMP.
      { move: COMP => /hasP [j_hp ARR /andP [NOTCOMP HP]].
        move: (ARR) => INarr.
        apply in_arrivals_implies_arrived_between in ARR; last by done.
        apply in_arrivals_implies_arrived in INarr.
          by exists j_hp; repeat split; last by apply/negP.
      }
      {
        apply negbT in COMP; rewrite -all_predC in COMP.
        move: COMP => /allP COMP.
        exfalso; apply NOTQUIET; intros j_hp IN HP ARR.
        destruct (ltnP (job_arrival j_hp) t1) as [BEFORE | AFTER];
          first by specialize (QUIET j_hp IN HP BEFORE); apply completion_monotonic with (t := t1).
        feed (COMP j_hp).
          by eapply arrived_between_implies_in_arrivals; eauto 1; apply/andP; split.
            by rewrite /= HP andbT negbK in COMP.
      }
    Qed.

  End ExistsPendingJob.

  (** In this section, we prove that during a busy interval the
         processor is never idle. *)
  Section ProcessorAlwaysBusy.

    (** Assume that the schedule is work-conserving ... *)
    Hypothesis H_work_conserving : work_conserving arr_seq sched.

    (** ... and the priority relation is reflexive and transitive. *)
    Hypothesis H_priority_is_reflexive : reflexive_priorities.
    Hypothesis H_priority_is_transitive : transitive_priorities.

    (** Consider any busy interval prefix <<[t1, t2)>>. *)
    Variable t1 t2 : instant.
    Hypothesis H_busy_interval_prefix : busy_interval_prefix t1 t2.

    (** We prove that if the processor is idle at a time instant t, then
           the next time instant [t+1] will be a quiet time. *)
    Lemma idle_time_implies_quiet_time_at_the_next_time_instant:
      forall (t : instant),
        is_idle sched t ->
        quiet_time t.+1.
    Proof.
      intros t IDLE jhp ARR HP AB.
      apply negbNE; apply/negP; intros NCOMP.
      rewrite /arrived_before ltnS in AB.
      move:(H_work_conserving _ t ARR) => WC.
      feed WC.
      { apply/andP. split.
        - apply/negPn/negP; rewrite negb_and; intros COMP.
          move: COMP => /orP; rewrite Bool.negb_involutive; move => [/negP CON|COM]; auto.
          move: NCOMP => /negP NCOMP; apply: NCOMP.
            by apply completion_monotonic with t.
        - by move: IDLE => /eqP IDLE; rewrite /scheduled_at scheduled_in_def IDLE.
      }
      move: IDLE WC => /eqP IDLE [jo SCHED].
        by rewrite scheduled_at_def IDLE in SCHED.
    Qed.

    (** Next, we prove that at any time instant t within the busy interval there exists a job
           [jhp] such that (1) job [jhp] is pending at time [t] and (2) job [jhp] has higher-or-equal
           priority than task [tsk]. *)
    Lemma pending_hp_job_exists:
      forall t,
        t1 <= t < t2 ->
        exists jhp,
          arrives_in arr_seq jhp /\
          job_pending_at jhp t /\
          hep_job jhp j.
    Proof.
      move => t /andP [GE LT]; move: (H_busy_interval_prefix) => [_ [QTt [NQT REL]]].
      move: (ltngtP t1.+1 t2) => [GT|CONTR|EQ]; first last.
      - subst t2; rewrite ltnS in LT.
        have EQ: t1 = t by apply/eqP; rewrite eqn_leq; apply/andP; split.
        subst t1; clear GE LT.
        exists j; repeat split; try done.
        + move: REL; rewrite ltnS -eqn_leq eq_sym; move => /eqP REL.
            by rewrite -REL; eapply job_pending_at_arrival; eauto 2.
        + by apply (H_priority_is_reflexive 0).
      - by exfalso; move_neq_down CONTR; eapply leq_ltn_trans; eauto 2.
      - have EX: exists hp__seq: seq Job,
        forall j__hp, j__hp \in hp__seq <-> arrives_in arr_seq j__hp /\ job_pending_at j__hp t /\ hep_job j__hp j.
        { exists (filter (fun jo => (job_pending_at jo t) && (hep_job jo j)) (arrivals_between 0 t.+1)).
          intros; split; intros T.
          - move: T; rewrite mem_filter; move => /andP [/andP [PEN HP] IN].
            repeat split; eauto using in_arrivals_implies_arrived.
          - move: T => [ARR [PEN HP]].
            rewrite mem_filter; apply/andP; split; first (apply/andP; split); try done.
            eapply arrived_between_implies_in_arrivals; try done.
              by apply/andP; split; last rewrite ltnS; move: PEN => /andP [T _].
        } move: EX => [hp__seq SE]; case FL: (hp__seq) => [ | jhp jhps].
        + subst hp__seq; exfalso.
          move: GE; rewrite leq_eqVlt; move => /orP [/eqP EQ| GE].
          * subst t.
            apply NQT with t1.+1; first by apply/andP; split.
            intros jhp ARR HP ARRB; apply negbNE; apply/negP; intros NCOMP.
            move: (SE jhp) => [_ SE2].
            rewrite in_nil in SE2; feed SE2; [clear SE2 | by done].
            repeat split; try done; first apply/andP; split; try done.
            apply/negP; intros COMLP.
            move: NCOMP => /negP NCOMP; apply: NCOMP.
              by apply completion_monotonic with t1.
          * apply NQT with t; first by apply/andP; split.
            intros jhp ARR HP ARRB; apply negbNE; apply/negP; intros NCOMP.
            move: (SE jhp) => [_ SE2].
            rewrite in_nil in SE2; feed SE2; [clear SE2 | by done].
              by repeat split; auto; apply/andP; split; first apply ltnW.
        + move: (SE jhp)=> [SE1 _]; subst; clear SE.
            by exists jhp; apply SE1; rewrite in_cons; apply/orP; left.
    Qed.

    (** We prove that at any time instant [t] within <<[t1, t2)>> the processor is not idle. *)
    Lemma not_quiet_implies_not_idle:
      forall t,
        t1 <= t < t2 ->
        ~ is_idle sched t.
    Proof.
      intros t NEQ IDLE.
      move: (pending_hp_job_exists _ NEQ) => [jhp [ARR [PEND HP]]].
      unfold work_conserving in *.
      feed (H_work_conserving _ t ARR).
      apply/andP; split; first by done.
      move: IDLE => /eqP IDLE; rewrite scheduled_at_def IDLE; by done.
      move: (H_work_conserving) => [jo SCHED].
      move: IDLE SCHED => /eqP IDLE SCHED.
        by rewrite scheduled_at_def IDLE in SCHED.
    Qed.

  End ProcessorAlwaysBusy.

  (** In section we prove a few auxiliary lemmas about quiet time and service.  *)
  Section QuietTimeAndServiceOfJobs.

    (** Assume that the schedule is work-conserving ... *)
    Hypothesis H_work_conserving : work_conserving arr_seq sched.

    (** ... and there are no duplicate job arrivals. *)
    Hypothesis H_arrival_sequence_is_a_set:
      arrival_sequence_uniq arr_seq.

    (** Let [t1] be a quiet time. *)
    Variable t1 : instant.
    Hypothesis H_quiet_time : quiet_time t1.

    (** Assume that there is no quiet time in the interval (t1, t1 + Δ]. *)
    Variable Δ : duration.
    Hypothesis H_no_quiet_time : forall t, t1 < t <= t1 + Δ -> ~ quiet_time t.

    (** For clarity, we introduce a notion of the total service of jobs released in
           time interval <<[t_beg, t_end)>> during the time interval [t1, t1 + Δ). *)
    Let service_received_by_hep_jobs_released_during t_beg t_end :=
      service_of_higher_or_equal_priority_jobs
        sched (arrivals_between t_beg t_end) j t1 (t1 + Δ).

    (** We prove that jobs with higher-than-or-equal priority that
           released before time instant t1 receive no service after
           time instant t1. *)
    Lemma hep_jobs_receive_no_service_before_quiet_time:
      service_received_by_hep_jobs_released_during t1 (t1 + Δ) =
      service_received_by_hep_jobs_released_during 0 (t1 + Δ).
    Proof.
      intros.
      rewrite /service_received_by_hep_jobs_released_during
              /service_of_higher_or_equal_priority_jobs
              /service_of_jobs /arrivals_between.
      rewrite [in X in _ = X](arrivals_between_cat _ _ t1);
        [ | | rewrite leq_addr]; try done.
      rewrite big_cat //=.
      rewrite -{1}[\sum_(j <- arrivals_between _ (t1 + Δ) | _)
                    service_during sched j t1 (t1 + Δ)]add0n.
      apply/eqP. rewrite eqn_add2r eq_sym exchange_big //=.
      rewrite big1_seq //.
      move => t' /andP [_ NEQ]; rewrite mem_iota in NEQ.
      rewrite big1_seq //.
      move => jhp /andP [HP ARR].
      apply/eqP; rewrite eqb0. rewrite -scheduled_at_def.
      apply (completed_implies_not_scheduled _ _ H_completed_jobs_dont_execute).
      apply completion_monotonic with t1; [ move: NEQ => /andP [T1 _] | ]; try done.
      apply H_quiet_time; try done.
      - by eapply in_arrivals_implies_arrived; eauto 2.
      - by eapply in_arrivals_implies_arrived_before; eauto 2.
    Qed.

    (** Next we prove that the total service within a "non-quiet"
        time interval <<[t1, t1 + Δ)>> is exactly Δ. *)
    Lemma no_idle_time_within_non_quiet_time_interval:
      service_of_jobs sched predT (arrivals_between 0 (t1 + Δ)) t1 (t1 + Δ) = Δ.
    Proof.
      intros; unfold service_of_jobs, service_of_higher_or_equal_priority_jobs.
      rewrite -{3}[Δ](sum_of_ones t1) exchange_big //=.
      apply/eqP; rewrite eqn_leq; apply/andP; split.
      { rewrite leq_sum //.
        move => t' _.
        have SCH := service_of_jobs_le_1 sched predT (arrivals_between 0 (t1 + Δ)) _ t'.
          by eauto using arrivals_uniq.
      }
      { rewrite [in X in X <= _]big_nat_cond [in X in _ <= X]big_nat_cond //=; rewrite leq_sum //.
        move => t' /andP [/andP [LT GT] _].
        apply/sum_seq_gt0P.
        ideal_proc_model_sched_case_analysis_eq sched t' jo.
        { exfalso; move: LT; rewrite leq_eqVlt; move => /orP [/eqP EQ|LT].
          { subst t'.
            feed (H_no_quiet_time t1.+1); first by apply/andP; split.
            apply: H_no_quiet_time.
              by apply idle_time_implies_quiet_time_at_the_next_time_instant.
          }
          { feed (H_no_quiet_time t'); first by apply/andP; split; last rewrite ltnW.
            apply: H_no_quiet_time; intros j_hp IN HP ARR.
            apply contraT; intros NOTCOMP.
            destruct (scheduled_at sched j_hp t') eqn:SCHEDhp;
              first by rewrite scheduled_at_def EqIdle in SCHEDhp.
            apply negbT in SCHEDhp.
            feed (H_work_conserving j_hp t' IN);
              first by repeat (apply/andP; split); first by apply ltnW.
            move: H_work_conserving => [j_other SCHEDother].
              by rewrite scheduled_at_def EqIdle in SCHEDother.
          }
        }
        { exists jo; split.
          - apply arrived_between_implies_in_arrivals; try done.
            apply H_jobs_come_from_arrival_sequence with t'; try done.
            apply/andP; split; first by done.
            apply H_jobs_must_arrive_to_execute in Sched_jo.
              by apply leq_ltn_trans with t'.
          - by rewrite lt0b -scheduled_at_def.
        }
      }
    Qed.

  End QuietTimeAndServiceOfJobs.

  (** In this section, we show that the length of any busy interval
      is bounded, as long as there is enough supply to accommodate
      the workload of tasks with higher or equal priority. *)
  Section BoundingBusyInterval.

    (** Assume that the schedule is work-conserving, ... *)
    Hypothesis H_work_conserving : work_conserving arr_seq sched.

    (** ... and there are no duplicate job arrivals, ... *)
    Hypothesis H_arrival_sequence_is_a_set:
      arrival_sequence_uniq arr_seq.

    (** ... and the priority relation is reflexive and transitive. *)
    Hypothesis H_priority_is_reflexive: reflexive_priorities.
    Hypothesis H_priority_is_transitive: transitive_priorities.

    (** Next, we recall the notion of workload of all jobs released in a given interval
           <<[t1, t2)>> that have higher-or-equal priority w.r.t the job j being analyzed. *)
    Let hp_workload t1 t2 :=
      workload_of_higher_or_equal_priority_jobs j (arrivals_between t1 t2).

    (** With regard to the jobs with higher-or-equal priority that are released
           in a given interval <<[t1, t2)>>, we also recall the service received by these
           jobs in the same interval [t1, t2). *)
    Let hp_service t1 t2 :=
      service_of_higher_or_equal_priority_jobs
        sched (arrivals_between t1 t2) j t1 t2.

    (** Now we begin the proof. First, we show that the busy interval is bounded. *)
    Section BoundingBusyInterval.

      (** Suppose that job j is pending at time t_busy. *)
      Variable t_busy : instant.
      Hypothesis H_j_is_pending : job_pending_at j t_busy.

      (** First, we show that there must exist a busy interval prefix. *)
      Section LowerBound.

        (** Since job j is pending, there is a (potentially unbounded)
               busy interval that starts no later than with the arrival of j. *)
        Lemma exists_busy_interval_prefix:
          exists t1,
            busy_interval_prefix t1 t_busy.+1 /\
            t1 <= job_arrival j <= t_busy.
        Proof.
          rename H_j_is_pending into PEND, H_work_conserving into WORK.
          destruct ([exists t:'I_t_busy.+1, quiet_time_dec t]) eqn:EX.
          - set last0 := \max_(t < t_busy.+1 | quiet_time_dec t) t.
            move: EX => /existsP [t EX].
            have PRED: quiet_time_dec last0 by apply (bigmax_pred t_busy.+1 (quiet_time_dec) t).
            have QUIET: quiet_time last0.
            { intros j_hp IN HP ARR; move: PRED => /allP PRED; feed (PRED j_hp).
              - by eapply arrived_between_implies_in_arrivals; eauto.
              - by rewrite HP implyTb in PRED.
            }
            exists last0.
            have JAIN: last0 <= job_arrival j <= t_busy.
            { apply/andP; split; last by move: PEND => /andP [ARR _].
              move_neq_up BEFORE.
              move: PEND => /andP [_ NOTCOMP].
              feed (QUIET j H_from_arrival_sequence); first by apply (H_priority_is_reflexive 0).
              specialize (QUIET BEFORE).
              apply completion_monotonic with (t' := t_busy) in QUIET; first by rewrite QUIET in NOTCOMP.
                by apply bigmax_ltn_ord with (i0 := t).
            }
            repeat split; try done.
            + by apply bigmax_ltn_ord with (i0 := t).
            + move => t0 /andP [GTlast LTbusy] QUIET0.
              have PRED0: quiet_time_dec t0.
              apply/allP; intros j_hp ARR; apply/implyP; intros HP.
              apply QUIET0; eauto 2 using in_arrivals_implies_arrived, in_arrivals_implies_arrived_before.
              move_neq_down GTlast.
                by eapply (@leq_bigmax_cond _ (fun (x: 'I_t_busy.+1) => quiet_time_dec x) (fun x => x) (Ordinal LTbusy)).
          -  apply negbT in EX; rewrite negb_exists in EX; move: EX => /forallP ALL.
             exists 0; split; last by apply/andP; split; last by move: PEND => /andP [ARR _].
             repeat split; first by intros j_hp _ _ ARR; rewrite /arrived_before ltn0 in ARR.
             move => t /andP [GE LT].
             specialize (ALL (Ordinal LT)); move: ALL => /negP ALL.
             intros QUIET; apply ALL; simpl.
             apply/allP; intros j_hp ARR; apply/implyP; intros HP.
             apply QUIET; eauto 2 using in_arrivals_implies_arrived, in_arrivals_implies_arrived_before.
             apply/andP; split; first by done.
               by move: PEND => /andP [ARR _].
        Qed.

      End LowerBound.

      (** Next we prove that, if there is a point where the requested workload
             is upper-bounded by the supply, then the busy interval eventually ends. *)
      Section UpperBound.

        (** Consider any busy interval prefix of job j. *)
        Variable t1 : instant.
        Hypothesis H_is_busy_prefix : busy_interval_prefix t1 t_busy.+1.

        (** Let priority_inversion_bound be a constant which bounds
             length of a priority inversion. *)
        Variable priority_inversion_bound: instant.
        Hypothesis H_priority_inversion_is_bounded:
          is_priority_inversion_bounded_by priority_inversion_bound.

        (** Next, assume that for some positive delta, the sum of requested workload
               at time [t1 + delta] and constant priority_inversion_bound is bounded by
               delta (i.e., the supply). *)
        Variable delta : duration.
        Hypothesis H_delta_positive : delta > 0.
        Hypothesis H_workload_is_bounded :
          priority_inversion_bound + hp_workload t1 (t1 + delta) <= delta.

        (** If there is a quiet time by time (t1 + delta), it trivially follows that
               the busy interval is bounded.
               Thus, let's consider first the harder case where there is no quiet time,
               which turns out to be impossible. *)
        Section CannotBeBusyForSoLong.

          (** Assume that there is no quiet time in the interval (t1, t1 + delta]. *)
          Hypothesis H_no_quiet_time:
            forall t, t1 < t <= t1 + delta -> ~ quiet_time t.

          (** Since the interval is always non-quiet, the processor is always busy
                 with tasks of higher-or-equal priority or some lower priority job which was scheduled,
                 i.e., the sum of service done by jobs with actual arrival time in <<[t1, t1 + delta)>>
                 and priority inversion equals delta. *)
          Lemma busy_interval_has_uninterrupted_service:
            delta <= priority_inversion_bound + hp_service t1 (t1 + delta).
          Proof.
            move: H_is_busy_prefix => [H_strictly_larger [H_quiet [_ EXj]]].
            destruct (delta <= priority_inversion_bound) eqn:KLEΔ.
            { by apply leq_trans with priority_inversion_bound; last rewrite leq_addr. }
            apply negbT in KLEΔ; rewrite -ltnNge in KLEΔ.
            apply leq_trans with (cumulative_priority_inversion sched j t1 (t1 + delta) + hp_service t1 (t1 + delta)).
            { rewrite /hp_service hep_jobs_receive_no_service_before_quiet_time //.
              rewrite /service_of_higher_or_equal_priority_jobs /service_of_jobs sum_pred_diff.
              rewrite addnBA; last first.
              { by rewrite big_mkcond //= leq_sum //; intros j' _; case (hep_job j' j). }
              rewrite addnC -addnBA.
              { intros. have TT := no_idle_time_within_non_quiet_time_interval.
                  by unfold service_of_jobs in TT; rewrite TT // leq_addr.
              }
              { rewrite /cumulative_priority_inversion /is_priority_inversion exchange_big //=.
                apply leq_sum_seq; move => t II _.
                rewrite mem_index_iota in II; move: II => /andP [GEi LEt].
                case SCHED: (sched t) => [j1 | ]; simpl; first last.
                { rewrite leqn0 big1_seq //. }
                { case PRIO1: (hep_job j1 j); simpl; first last.
                  - rewrite <- SCHED.
                    have SCH := service_of_jobs_le_1 sched _ _ _ t; eauto using arrivals_uniq.
                  - rewrite leqn0 big1_seq; first by done.
                    move => j2 /andP [PRIO2 ARRj2].
                    case EQ: (j1 == j2).
                    + by move: EQ => /eqP EQ; subst j2; rewrite PRIO1 in PRIO2.
                    + apply/eqP; rewrite eqb0; apply/negP; intros CONTR; move: CONTR => /eqP CONTR.
                        by inversion CONTR; clear CONTR; subst j2; rewrite PRIO1 in PRIO2. } } }
            { rewrite leq_add2r.
              destruct (t1 + delta <= t_busy.+1) eqn:NEQ; [ | apply negbT in NEQ; rewrite -ltnNge in NEQ].
              - apply leq_trans with (cumulative_priority_inversion sched j t1 t_busy.+1); last eauto 2.
                  by rewrite [X in _ <= X](@big_cat_nat _ _ _ (t1 + delta)) //=; rewrite leq_addr.
              -  apply H_priority_inversion_is_bounded; repeat split; try done.
                 + by rewrite -addn1 leq_add2l.
                 + move => t' /andP [LT GT]; apply H_no_quiet_time.
                     by apply/andP; split; [ | rewrite ltnW ].
                 + move: EXj => /andP [T1 T2].
                     by apply/andP; split; [done | apply ltn_trans with (t_busy.+1)].
            }
          Qed.

          (** Moreover, the fact that the interval is not quiet also implies
                 that there's more workload requested than service received. *)
          Lemma busy_interval_too_much_workload:
            hp_workload t1 (t1 + delta) > hp_service t1 (t1 + delta).
          Proof.
            have PEND := not_quiet_implies_exists_pending_job.
            rename H_no_quiet_time into NOTQUIET,
            H_is_busy_prefix into PREFIX.
            set l := arrivals_between t1 (t1 + delta).
            set hep := hep_job.
            unfold hp_service, service_of_higher_or_equal_priority_jobs, service_of_jobs,
            hp_workload, workload_of_higher_or_equal_priority_jobs, workload_of_jobs.
            fold arrivals_between l hep.
            move: (PREFIX) => [_ [QUIET _]].
            move: (NOTQUIET) => NOTQUIET'.
            feed (NOTQUIET' (t1 + delta)).
            { by apply/andP; split; first
                by rewrite -addn1 leq_add2l.
            }
            feed (PEND t1 (t1 + delta)); first by apply leq_addr.
            specialize (PEND QUIET NOTQUIET').
            move: PEND => [j0 [ARR0 [/andP [GE0 LT0] [HP0 NOTCOMP0]]]].
            have IN0: j0 \in l.
            { by eapply arrived_between_implies_in_arrivals; eauto 1; apply/andP; split. }
            have UNIQ: uniq l by eapply arrivals_uniq; eauto 1.
            rewrite big_mkcond [\sum_(_ <- _ | _ _ _)_]big_mkcond //=.
            rewrite (bigD1_seq j0); [simpl | by done | by done].
            rewrite (bigD1_seq j0); [simpl | by done | by done].
            rewrite /hep HP0.
            rewrite -add1n addnA [1 + _]addnC addn1.
            apply leq_add; last first.
            {
              apply leq_sum; intros j1 NEQ.
              destruct (hep_job j1 j); last by done.
                by apply cumulative_service_le_job_cost, ideal_proc_model_provides_unit_service.
            }
            rewrite ignore_service_before_arrival; rewrite //; [| by apply ltnW].
            rewrite <- ignore_service_before_arrival with (t2:=0); rewrite //; [|by apply ltnW].
              by rewrite ltnNge; apply/negP.
          Qed.

          (** Using the two lemmas above, we infer that the workload is larger than the
                 interval length. However, this contradicts the assumption H_workload_is_bounded. *)
          Corollary busy_interval_workload_larger_than_interval:
            priority_inversion_bound + hp_workload t1 (t1 + delta)  > delta.
          Proof.
            apply leq_ltn_trans with (priority_inversion_bound + hp_service t1 (t1 + delta)).
            apply busy_interval_has_uninterrupted_service.
            rewrite ltn_add2l.
            apply busy_interval_too_much_workload.
          Qed.

        End CannotBeBusyForSoLong.

        (** Since the interval cannot remain busy for so long, we prove that
               the busy interval finishes at some point t2 <= t1 + delta. *)
        Lemma busy_interval_is_bounded:
          exists t2,
            t2 <= t1 + delta /\
            busy_interval t1 t2.
        Proof.
          move: H_is_busy_prefix => [LT [QT [NQ NEQ]]].
          destruct ([exists t2:'I_(t1 + delta).+1, (t2 > t1) && quiet_time_dec t2]) eqn:EX.
          - have EX': exists (t2 : instant), ((t1 < t2 <= t1 + delta) && quiet_time_dec t2).
            { move: EX => /existsP [t2 /andP [LE QUIET]].
              exists t2; apply/andP; split; last by done.
                by apply/andP; split; last (rewrite -ltnS; apply ltn_ord). }
            move: (ex_minnP EX') => [t2 /andP [/andP [GT LE] QUIET] MIN]; clear EX EX'.
            exists t2; split; [ | split; [repeat split | ]]; try done.
            + move => t /andP [GT1 LT2] BUG.
              feed (MIN t); first (apply/andP; split).
              * by apply/andP; split; last by apply leq_trans with (n := t2); eauto using ltnW.
              * apply/allP; intros j_hp ARR; apply/implyP; intro HP.
                apply BUG; eauto 2 using in_arrivals_implies_arrived, ARR, in_arrivals_implies_arrived_before.
                  by apply leq_ltn_trans with (p := t2) in MIN; first by rewrite ltnn in MIN.
            + move: NEQ => /andP [IN1 IN2].
              apply/andP; split; first by done.
              apply leq_ltn_trans with t_busy; eauto 2.
              rewrite ltnNge; apply/negP; intros CONTR.
              apply NQ with t2.
              * by apply/andP; split; last rewrite ltnS.
              * intros jhp ARR HP AB.
                move: QUIET => /allP QUIET; feed (QUIET jhp).
                eapply arrived_between_implies_in_arrivals; eauto 2.
                  by move: QUIET => /implyP QUIET; apply QUIET.
            + intros j_hp IN HP ARR.
              move: QUIET => /allP QUIET; feed (QUIET j_hp).
              * by eapply arrived_between_implies_in_arrivals; last apply ARR.
              * by move: QUIET => /implyP QUIET; apply QUIET.
          - apply negbT in EX; rewrite negb_exists in EX; move: EX => /forallP ALL'.
            have ALL: forall t, t1 < t <= t1 + delta -> ~ quiet_time t.
            { move => t /andP [GTt LEt] QUIET; rewrite -ltnS in LEt.
              specialize (ALL' (Ordinal LEt)); rewrite negb_and /= GTt orFb in ALL'.
              move: ALL' => /negP ALL'; apply ALL'; clear ALL'.
              apply/allP; intros j_hp ARR; apply/implyP; intro HP.
              apply QUIET; eauto 2 using in_arrivals_implies_arrived, ARR, in_arrivals_implies_arrived_before.
            } clear ALL'; exfalso.
            have TOOMUCH := busy_interval_workload_larger_than_interval.
            have BOUNDED := H_workload_is_bounded.
              by move: (leq_trans (TOOMUCH ALL) BOUNDED); rewrite ltnn.
        Qed.

      End UpperBound.

    End BoundingBusyInterval.

    (** In this section, we show that from a workload bound we can infer
           the existence of a busy interval. *)
    Section BusyIntervalFromWorkloadBound.

      (** Let priority_inversion_bound be a constant that bounds the length of a priority inversion. *)
      Variable priority_inversion_bound: duration.
      Hypothesis H_priority_inversion_is_bounded:
        is_priority_inversion_bounded_by priority_inversion_bound.

      (** Assume that for some positive delta, the sum of requested workload at
             time (t1 + delta) and priority inversion is bounded by delta (i.e., the supply). *)
      Variable delta: duration.
      Hypothesis H_delta_positive: delta > 0.
      Hypothesis H_workload_is_bounded:
        forall t, priority_inversion_bound + hp_workload t (t + delta) <= delta.

      (** Next, we assume that job j has positive cost, from which we can
             infer that there is a time in which j is pending. *)
      Hypothesis H_positive_cost: job_cost j > 0.

      (** Therefore there must exists a busy interval <<[t1, t2)>> that
             contains the arrival time of j. *)
      Corollary exists_busy_interval:
        exists t1 t2,
          t1 <= job_arrival j < t2 /\
          t2 <= t1 + delta /\
          busy_interval t1 t2.
      Proof.
        have PREFIX := exists_busy_interval_prefix.
        move: (H_workload_is_bounded) => WORK.
        feed (PREFIX (job_arrival j)).
        { apply/andP; split; first by apply leqnn.
          rewrite /completed_by /service.
          rewrite ignore_service_before_arrival // /service_during.
          rewrite big_geq; last by apply leqnn.
            by rewrite -ltnNge.
        }
        move: PREFIX => [t1 [PREFIX /andP [GE1 GEarr]]].
        have BOUNDED := busy_interval_is_bounded
                          (job_arrival j) t1  PREFIX priority_inversion_bound _ delta
                          H_delta_positive.
        feed_n 2 BOUNDED; try done.
        move: BOUNDED => [t2 [GE2 BUSY]].
        exists t1, t2; split.
        { apply/andP; split; first by done.
          apply contraT; rewrite -leqNgt; intro BUG.
          move: BUSY PREFIX => [[LE12 _] QUIET] [_ [_ [NOTQUIET _]]].
          feed (NOTQUIET t2); first by apply/andP; split.
            by exfalso; apply NOTQUIET.
        }
          by split.
      Qed.

    End BusyIntervalFromWorkloadBound.

    (** If we know that the workload is bounded, we can also use the
           busy interval to infer a response-time bound. *)
    Section ResponseTimeBoundFromBusyInterval.

      (** Let priority_inversion_bound be a constant that bounds the length of a priority inversion. *)
      Variable priority_inversion_bound: duration.
      Hypothesis H_priority_inversion_is_bounded:
        is_priority_inversion_bounded_by priority_inversion_bound.

      (** Assume that for some positive delta, the sum of requested workload at
             time (t1 + delta) and priority inversion is bounded by delta (i.e., the supply). *)
      Variable delta: duration.
      Hypothesis H_delta_positive: delta > 0.
      Hypothesis H_workload_is_bounded:
        forall t, priority_inversion_bound + hp_workload t (t + delta) <= delta.

      (** Then, job j must complete by (job_arrival j + delta). *)
      Lemma busy_interval_bounds_response_time:
        job_completed_by j (job_arrival j + delta).
      Proof.
        have BUSY := exists_busy_interval priority_inversion_bound _ delta.
        move: (posnP (@job_cost _ H2 j)) => [ZERO|POS].
        { by rewrite /job_completed_by /completed_by ZERO. }
        feed_n 4 BUSY; try by done.
        move: BUSY => [t1 [t2 [/andP [GE1 LT2] [GE2 BUSY]]]].
        apply completion_monotonic with (t := t2); try (by done);
          first by apply leq_trans with (n := t1 + delta); [| by rewrite leq_add2r].
        apply job_completes_within_busy_interval with (t1 := t1); try by done.
      Qed.

    End ResponseTimeBoundFromBusyInterval.

  End BoundingBusyInterval.

End ExistsBusyIntervalJLFP.


Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.

Derive Show for natural.

              Derive Arbitrary for natural.

              Instance Dec_Eq_natural : Dec_Eq natural.

              Proof. dec_eq. Qed.

Lemma conj9synthconj2 : forall  (lv0 : natural) (lv1 : natural), (@eq natural (plus (mult lv0 lv1) lv0) (plus (mult lv1 lv0) lv0)).
Admitted.
QuickChick conj9synthconj2.


From iris.program_logic Require Export total_adequacy.
From iris.heap_lang Require Export adequacy.
From iris.heap_lang Require Import proofmode notation.
From iris.proofmode Require Import tactics.
Set Default Proof Using "Type".

Definition heap_total Σ `{heapPreG Σ} s e σ φ :
  (∀ `{heapG Σ}, WP e @ s; ⊤ [{ v, ⌜φ v⌝ }]%I) →
  sn erased_step ([e], σ).
Proof.
  intros Hwp; eapply (twp_total _ _); iIntros (?) "".
  iMod (gen_heap_init σ.(heap)) as (?) "Hh".
  iMod (proph_map_init [] σ.(used_proph_id)) as (?) "Hp".
  iModIntro.
  iExists
    (λ σ κs _, (gen_heap_ctx σ.(heap) ∗ proph_map_ctx κs σ.(used_proph_id))%I),
    (λ _, True%I); iFrame.
  iApply (Hwp (HeapG _ _ _ _)).
Qed.


(**
pullback of coproducts
 Coproducts of arities using LModule Coproducts (more
conveninent than LModule.Colims)
 *)
Require Import UniMath.Foundations.PartD.
Require Import UniMath.Foundations.Propositions.
Require Import UniMath.Foundations.Sets.
Require Import UniMath.CategoryTheory.Core.Prelude.
Require Import UniMath.CategoryTheory.FunctorCategory.

Require Import UniMath.CategoryTheory.Monads.Monads.
Require Import UniMath.CategoryTheory.Monads.LModules.

Require Import UniMath.CategoryTheory.DisplayedCats.Core.
Require Import UniMath.CategoryTheory.DisplayedCats.Constructions.

Require Import UniMath.CategoryTheory.limits.coproducts.
Require Import UniMath.CategoryTheory.limits.graphs.colimits.

Require Import Modules.Prelims.lib.
Require Import Modules.Prelims.CoproductsComplements.

Require Import Modules.Prelims.LModulesCoproducts.
Require Import Modules.Signatures.Signature.

Section Coprod.
  Context {C : category} .

  Context {O : UU}.
  Context {cpC : Coproducts O C}.

  Local Notation hsC := (homset_property C).

  Local Notation Signature := (signature C).
  Local Notation MOD R := (category_LModule R C).

  Let cpLM (X : Monad C) := LModule_Coproducts C  X cpC.
  Let cpFunc := Coproducts_functor_precat _ C _ cpC .

  (* Local Notation SIGNATURE := (signature C). *)

  Context (α : O -> Signature).
  Local Notation α' R := (fun o => α o R).

  Definition signature_coprod_on_objects (R : Monad C) : LModule R C :=
    CoproductObject _ _ (cpLM R (α' R)).

  Definition signature_coprod_on_morphisms (R S : Monad C)
             (f : Monad_Mor R S) : LModule_Mor _ (signature_coprod_on_objects R)
                                               (pb_LModule f (signature_coprod_on_objects S)).
    eapply (compose (C := (MOD _))); revgoals.
    - cbn.
      apply coprod_pbm_to_pbm_coprod.
    - apply  (CoproductOfArrows _ _ (cpLM R _) (cpLM R _)).
      intro o.
      exact ((# (α o) f)%ar).
  Defined.

  Definition signature_coprod_data : @signature_data C
    := signature_coprod_on_objects ,, signature_coprod_on_morphisms.

  Lemma signature_coprod_is_signature : is_signature signature_coprod_data.
  Proof.
    split.
    - intros R c.
      cbn  -[CoproductOfArrows].
      rewrite id_right.
      apply pathsinv0.
      apply CoproductArrowUnique.
      intro o.
      etrans;[apply id_right|].
      apply pathsinv0.
      etrans;[|apply id_left].
      apply cancel_postcomposition.
      apply signature_id.
    - intros R S T f g.
      apply LModule_Mor_equiv.
      + apply homset_property.
      + apply nat_trans_eq.
        apply homset_property.
        intro x.
        cbn  -[CoproductOfArrows ].
        repeat  rewrite id_right.
        apply pathsinv0.
        etrans; [apply CoproductOfArrows_comp|].
        apply CoproductOfArrows_eq.
        apply funextsec.
        intro i.
        assert (h := signature_comp (α i) f g).
        apply LModule_Mor_equiv in h;[|apply homset_property].
        eapply nat_trans_eq_pointwise in h.
        apply pathsinv0.
        etrans;[eapply h|].
        cbn.
        rewrite id_right.
        apply idpath.
  Qed.

  Definition signature_coprod : Signature := _ ,, signature_coprod_is_signature.

  Lemma signature_coproductIn_laws o :
    is_signature_Mor (α o) signature_coprod
                 (fun R => CoproductIn  _ _  (cpLM R (fun o => α o R)) o  ).
  Proof.
    intros R S f.
    apply nat_trans_eq;[apply homset_property|].
    intro x.
    cbn -[CoproductIn CoproductOfArrows].
    rewrite id_right.
    apply pathsinv0.
    cbn.
    unfold coproduct_nat_trans_in_data.
    set (CC := cpC _).
    use (CoproductOfArrowsIn _ _ CC).
  Qed.

  Definition signature_coproductIn o :
    signature_Mor  (α o) signature_coprod := _ ,, signature_coproductIn_laws o.

  (* TODO : move to Signature *)
  Definition signature_coproductArrow_laws {b : Signature} (cc : ∏ o, signature_Mor (α o) b ) :
    is_signature_Mor
      signature_coprod b
      (fun R => CoproductArrow  _ _  (cpLM R (fun o => α o R)) (c := b R) (fun o => cc o R)).
  Proof.
    intros R S f.
    apply nat_trans_eq;[apply homset_property|].
    intro x.
    cbn -[CoproductIn CoproductOfArrows].
    rewrite id_right.
    unfold coproduct_nat_trans_data.
    etrans;[apply precompWithCoproductArrow|].
    cbn.
    apply pathsinv0.
    apply CoproductArrowUnique.
    intro o.
    cbn.
    etrans.
    {
      etrans;[apply assoc|].
      apply cancel_postcomposition.
      set (CC := cpC _).
      apply (CoproductInCommutes _ _ _ CC).
    }
    apply pathsinv0.
    apply signature_Mor_ax_pw.
  Qed.

  Definition signature_coproductArrow {b : Signature} (cc : ∏ o, signature_Mor (α o) b ) :
    signature_Mor signature_coprod b := _ ,, signature_coproductArrow_laws cc.

  Lemma signature_isCoproduct : isCoproduct _ signature_category   _ _ signature_coproductIn.
  Proof.
    intros b cc.
    use unique_exists.
    - exact (signature_coproductArrow cc).
    - intro v.
      apply signature_Mor_eq.
      intro R.
      apply (CoproductInCommutes  _ (MOD R) _ (cpLM R (fun o => α o R))).
    - intro y.
      cbn -[isaprop].
      apply impred_isaprop.
      intro o.
      apply signature_category_has_homsets.
    - intros y h.
      apply signature_Mor_eq.
      intro R.
      apply (CoproductArrowUnique  _ (MOD R) _ (cpLM R (fun o => α o R))).
      cbn in h.
      intro i.
      specialize (h i).
      rewrite <- h.
      apply idpath.
  Defined.

  Definition signature_Coproduct : Coproduct _ signature_category α :=
    make_Coproduct  _ _ _ _ _ signature_isCoproduct.

End Coprod.

Definition signature_Coproducts {C : category}
           {O : UU}
           (cpC : Coproducts O C)
            : Coproducts O (signature_category (C := C)) :=
   signature_Coproduct (cpC := cpC).


Require Import Coq.omega.Omega.
Require Import Bedrock.Word Bedrock.SepIL Bedrock.IL Bedrock.Memory.

Fixpoint allocated (base : W) (offset len : nat) : HProp :=
  match len with
    | O => Emp
    | S len' => (Ex v, (match offset with
                          | O => base
                          | _ => base ^+ $ (offset)
                        end) =*> v) * allocated base (4+offset) len'
  end%Sep.

Notation "p =?> len" := (allocated p O len) (at level 39) : Sep_scope.

Theorem allocated_extensional : forall base offset len, HProp_extensional (allocated base offset len).
  destruct len; reflexivity.
Qed.

Hint Immediate allocated_extensional.

Lemma Himp_refl : forall p, p ===> p.
  intros; hnf; intros; hnf; intros.
  apply PropX.Imply_I.
  apply PropX.Env.
  simpl; auto.
Qed.

Lemma allocated_shift_base' : forall base base' len offset offset',
  base ^+ $ (offset) = base' ^+ $ (offset')
  -> allocated base offset len ===> allocated base' offset' len.
Proof.
  induction len; intros.

  apply Himp_refl.

  unfold allocated; fold allocated.
  match goal with
    | [ |- context[(?X =*> _)%Sep] ] =>
      assert (X = base ^+ natToW offset)
  end.
  destruct offset; auto.
  W_eq.
  rewrite H0; clear H0.

  match goal with
    | [ |- context[(?X =*> _)%Sep] ] =>
      match X with
        | context[offset'] => assert (X = base' ^+ natToW offset')
      end
  end.
  destruct offset'; auto.
  W_eq.
  rewrite H0; clear H0.

  match goal with
    | [ H : ?X = _ |- context[(?Y =*> _)%Sep] ] => change Y with X; rewrite H
  end.
  intro. apply himp_star_frame. apply himp_ex. reflexivity.
  eapply IHlen. repeat rewrite natToW_plus.
  repeat rewrite (wplus_comm (natToW 4)).
  repeat rewrite wplus_assoc.
  unfold natToW in *. rewrite H. reflexivity.
Qed.

Theorem allocated_shift_base : forall base base' len len' offset offset',
  base ^+ $ (offset) = base' ^+ $ (offset')
  -> len = len'
  -> allocated base offset len ===> allocated base' offset' len'.
  intros; subst; apply allocated_shift_base'; auto.
Qed.

Lemma disjoint'_emp : forall addrs, disjoint' addrs (smem_emp' _) (smem_emp' _).
  induction addrs; simpl; intuition.
Qed.

Lemma join'_emp : forall addrs, smem_emp' _ = join' addrs (smem_emp' _) (smem_emp' _).
  induction addrs; simpl; intuition.
  congruence.
Qed.

Lemma split_empty : forall m, semp m
  -> split m m m.
  unfold semp; intros; subst.
  split.
  apply disjoint'_emp.

  apply join'_emp.
Qed.

Theorem allocated_split : forall base len' len offset,
  (len' <= len)%nat
  -> allocated base offset len ===> allocated base offset len' * allocated base (offset + 4 * len') (len - len').
Proof.
  induction len'; inversion 1.
  { simpl. intro. unfold empB, starB.
    rewrite heq_star_emp_r. reflexivity. }
  { replace (offset + 4 * 0) with offset by omega.
    simpl minus.
    unfold allocated at 2. unfold empB, starB. intro. rewrite heq_star_emp_l. reflexivity. }
  { replace (S len' - S len') with 0 by omega. intro.
    unfold allocated at 3. unfold empB, starB. rewrite heq_star_emp_r. reflexivity. }
  { subst.
    replace (offset + 4 * S len') with ((4 + offset) + 4 * len') by omega.
    unfold allocated at 1 2; fold allocated.
    unfold empB, starB, exB. intro.
    rewrite heq_star_assoc.
    repeat rewrite heq_ex_star.
    apply himp_ex. intros.
    apply himp_star_frame. reflexivity.
    simpl minus. eapply IHlen'. omega. }
Qed.

Theorem allocated_join : forall base len' len offset,
  (len' <= len)%nat
  -> allocated base offset len' * allocated base (offset + 4 * len') (len - len') ===> allocated base offset len.
Proof.
  induction len'; inversion 1.
  { intro; unfold starB, empB; simpl. rewrite heq_star_emp_r. reflexivity. }
  { replace (offset + 4 * 0) with offset by omega.
    simpl minus.
    unfold allocated at 1. unfold empB, starB. intro. rewrite heq_star_emp_l. reflexivity. }
  { replace (S len' - S len') with 0 by omega. intro.
    unfold allocated at 3. unfold empB, starB. rewrite heq_star_emp_r. reflexivity. }
  { subst.
    replace (offset + 4 * S len') with ((4 + offset) + 4 * len') by omega.
    unfold allocated at 1 3; fold allocated.
    unfold empB, starB, exB. intro.
    rewrite heq_star_assoc.
    repeat rewrite heq_ex_star.
    apply himp_ex. intros.
    apply himp_star_frame. reflexivity.
    simpl minus. eapply IHlen'. omega. }
Qed.


(*********************************************************************************

 The total category of a displayed monoidal category

 In this file, we show that the total category of a displayed monoidal category is
 again a monoidal category.

Note: after refactoring on March 10, 2023, the prior Git history of this development is found via
git log -- UniMath/CategoryTheory/Monoidal/TotalDisplayedMonoidalWhiskered.v

 *********************************************************************************)
Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.
Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.Core.NaturalTransformations.
Require Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.
Require Import UniMath.CategoryTheory.Monoidal.Categories.
Require Import UniMath.CategoryTheory.Monoidal.Displayed.WhiskeredDisplayedBifunctors.
Require Import UniMath.CategoryTheory.Monoidal.Displayed.Monoidal.
Require Import UniMath.CategoryTheory.Monoidal.Functors.
Require Import UniMath.CategoryTheory.DisplayedCats.Core.
Require Import UniMath.CategoryTheory.DisplayedCats.Functors.
Require Import UniMath.CategoryTheory.DisplayedCats.Constructions.
Require Import UniMath.CategoryTheory.DisplayedCats.Total.

Local Open Scope cat.
Local Open Scope mor_disp_scope.

Section MonoidalTotalCategory.

  Import BifunctorNotations.
  Import MonoidalNotations.
  Import DisplayedBifunctorNotations.
  Import DisplayedMonoidalNotations.

  Local Notation "T( D )" := (total_category D).

  (** DATA **)
  Definition total_tensor_data
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DT : disp_tensor D M)
    : bifunctor_data T(D) T(D) T(D).
  Proof.
    use make_bifunctor_data.
    - intros x y.
      exact (pr1 x ⊗_{M} pr1 y ,, pr2 x ⊗⊗_{DT} pr2 y).
    - intros x y1 y2 g.
      exact (pr1 x ⊗^{M}_{l} pr1 g ,, pr2 x ⊗⊗^{DT}_{l} pr2 g).
    - intros y x1 x2 f.
      exact (pr1 f ⊗^{M}_{r} pr1 y ,, pr2 f ⊗⊗^{DT}_{r} pr2 y).
  Defined.

  Lemma total_leftidax
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DT : disp_tensor D M)
    : bifunctor_leftidax (total_tensor_data DT).
  Proof.
    intros x y.
    use total2_paths_b.
    - exact (bifunctor_leftid (monoidal_tensor M) (pr1 x) (pr1 y)).
    - exact (disp_bifunctor_leftid DT (pr1 x) (pr1 y) (pr2 x) (pr2 y)).
  Qed.

  Lemma total_rightidax
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DT : disp_tensor D M)
    : bifunctor_rightidax (total_tensor_data DT).
  Proof.
    intros y x.
    use total2_paths_b.
    - exact (bifunctor_rightid (monoidal_tensor M) (pr1 y) (pr1 x)).
    - exact (disp_bifunctor_rightid DT (pr1 x) (pr1 y) (pr2 x) (pr2 y)).
  Qed.

  Lemma total_leftcompax
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DT : disp_tensor D M)
    : bifunctor_leftcompax (total_tensor_data DT).
  Proof.
    intros x y1 y2 y3 g1 g2.
    use total2_paths_b.
    - exact (bifunctor_leftcomp
               (monoidal_tensor M)
               (pr1 x) (pr1 y1) (pr1 y2) (pr1 y3)
               (pr1 g1) (pr1 g2)).
    - exact (disp_bifunctor_leftcomp
               DT
               (pr1 x) (pr1 y1) (pr1 y2) (pr1 y3)
               (pr1 g1) (pr1 g2)
               (pr2 x) (pr2 y1) (pr2 y2) (pr2 y3)
               (pr2 g1) (pr2 g2)).
  Qed.

  Lemma total_rightcompax
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DT : disp_tensor D M)
    : bifunctor_rightcompax (total_tensor_data DT).
  Proof.
    intros y x1 x2 x3 f1 f2.
    use total2_paths_b.
    - exact (bifunctor_rightcomp
               (monoidal_tensor M)
               (pr1 y) (pr1 x1) (pr1 x2) (pr1 x3)
               (pr1 f1) (pr1 f2)).
    - exact (disp_bifunctor_rightcomp DT
               (pr1 x1) (pr1 x2) (pr1 x3) (pr1 y)
               (pr1 f1) (pr1 f2)
               (pr2 x1) (pr2 x2) (pr2 x3) (pr2 y)
               (pr2 f1) (pr2 f2)).
  Qed.

  Lemma total_functoronmorphisms_are_equal
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DT : disp_tensor D M)
    : functoronmorphisms_are_equal (total_tensor_data DT).
  Proof.
    intros x1 x2 y1 y2 f g.
    use total2_paths_b.
    - exact (bifunctor_equalwhiskers
               (monoidal_tensor M)
               (pr1 x1) (pr1 x2)
               (pr1 y1) (pr1 y2)
               (pr1 f) (pr1 g)).
    - exact (disp_bifunctor_equalwhiskers
               DT
               (pr1 x1) (pr1 x2) (pr1 y1) (pr1 y2)
               (pr1 f) (pr1 g)
               (pr2 x1) (pr2 x2) (pr2 y1) (pr2 y2)
               (pr2 f) (pr2 g)).
  Qed.

  Definition total_tensor
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DT : disp_tensor D M)
    : bifunctor T(D) T(D) T(D)
    := (total_tensor_data DT
        ,, total_leftidax DT
        ,, total_rightidax DT
        ,, total_leftcompax DT
        ,, total_rightcompax DT
        ,, total_functoronmorphisms_are_equal DT).

  Local Notation Tt := total_tensor_data.

  Definition total_unit
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DT : disp_tensor D M)
             (i : D I_{M})
    : T(D)
    := (I_{M},,i).

  Notation Tu := total_unit.

  Definition total_leftunitordata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             {i : D I_{M}}
             (dlu : disp_leftunitor_data DT i)
    : leftunitor_data (Tt DT) (Tu DT i).
  Proof.
    intro x.
    use tpair.
    - exact (lu_{M} (pr1 x)).
    - exact (dlu (pr1 x) (pr2 x)).
  Defined.

  Definition total_leftunitorinvdata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             {i : D I_{M}}
             (dluinv : disp_leftunitorinv_data DT i)
    : leftunitorinv_data (Tt DT) (Tu DT i).
  Proof.
    intro x.
    use tpair.
    - exact (luinv_{M} (pr1 x)).
    - exact (dluinv (pr1 x) (pr2 x)).
  Defined.

  Definition total_rightunitordata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             {i : D I_{M}}
             (dru : disp_rightunitor_data DT i)
    : rightunitor_data (Tt DT) (Tu DT i).
  Proof.
    intro x.
    use tpair.
    - exact (ru_{M} (pr1 x)).
    - exact (dru (pr1 x) (pr2 x)).
  Defined.

  Definition total_rightunitorinvdata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             {i : D I_{M}}
             (druinv : disp_rightunitorinv_data DT i)
    : rightunitorinv_data (Tt DT) (Tu DT i).
  Proof.
    intro x.
    use tpair.
    - exact (ruinv_{M} (pr1 x)).
    - exact (druinv (pr1 x) (pr2 x)).
  Defined.

  Definition total_associatordata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             (dα : disp_associator_data DT)
    : associator_data (Tt DT).
  Proof.
    intros x y z.
    use tpair.
    - exact (α_{M} (pr1 x) (pr1 y) (pr1 z)).
    - exact (dα (pr1 x) (pr1 y) (pr1 z) (pr2 x) (pr2 y) (pr2 z)).
  Defined.

  Notation Tα := total_associatordata.

  Definition total_associatorinvdata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             {DT : disp_tensor D M}
             (dαinv : disp_associatorinv_data DT)
    : associatorinv_data (Tt DT).
  Proof.
    intros x y z.
    use tpair.
    - exact (αinv_{M} (pr1 x) (pr1 y) (pr1 z)).
    - exact (dαinv (pr1 x) (pr1 y) (pr1 z) (pr2 x) (pr2 y) (pr2 z)).
  Defined.

  Definition total_monoidaldata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal_data D M)
    : monoidal_data T(D).
  Proof.
    use make_monoidal_data.
    - exact (total_tensor_data DM).
    - exact (total_unit DM dI_{DM}).
    - exact (total_leftunitordata dlu^{DM}).
    - exact (total_leftunitorinvdata dluinv^{DM}).
    - exact (total_rightunitordata dru^{DM}).
    - exact (total_rightunitorinvdata druinv^{DM}).
    - exact (total_associatordata dα^{DM}).
    - exact (total_associatorinvdata dαinv^{DM}).
  Defined.

  (** PROPERTIES **)
  Lemma total_leftunitor_iso_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dluiso : disp_leftunitor_iso dlu^{DM} dluinv^{DM})
    : leftunitor_iso_law
        (total_leftunitordata dlu^{DM})
        (total_leftunitorinvdata dluinv^{DM}).
  Proof.
    intros x.
    split.
    - use total2_paths_b.
      + exact (pr1 (pr2 (monoidal_leftunitorlaw M) (pr1 x))).
      + exact (pr2 (dluiso (pr1 x) (pr2 x))).
    - use total2_paths_b.
        * exact (pr2 (pr2 (monoidal_leftunitorlaw M) (pr1 x))).
        * exact (pr1 (dluiso (pr1 x) (pr2 x))).
  Qed.

  Lemma total_leftunitor_nat
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dluiso : disp_leftunitor_nat dlu^{DM})
    : leftunitor_nat (total_leftunitordata dlu^{DM}).
  Proof.
    intros x y f.
    use total2_paths_b.
    - exact ((pr1 (monoidal_leftunitorlaw M)) (pr1 x) (pr1 y) (pr1 f)).
    - exact (dluiso (pr1 x) (pr1 y) (pr1 f) (pr2 x) (pr2 y) (pr2 f)).
  Defined.

  Lemma total_leftunitor_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dluiso : disp_leftunitor_law dlu^{DM} dluinv^{DM})
    : leftunitor_law
        (total_leftunitordata dlu^{DM})
        (total_leftunitorinvdata dluinv^{DM}).
  Proof.
    exact (total_leftunitor_nat (pr1 dluiso),,total_leftunitor_iso_law (pr2 dluiso)).
  Defined.

  Lemma total_rightunitor_iso_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (druiso : disp_rightunitor_iso dru^{DM} druinv^{DM})
    : rightunitor_iso_law
        (total_rightunitordata dru^{DM})
        (total_rightunitorinvdata druinv^{DM}).
  Proof.
    intros x.
    split.
    - use total2_paths_b.
      + exact (pr1 (pr2 (monoidal_rightunitorlaw M) (pr1 x))).
      + exact (pr2 (druiso (pr1 x) (pr2 x))).
    - use total2_paths_b.
        * exact (pr2 (pr2 (monoidal_rightunitorlaw M) (pr1 x))).
        * exact (pr1 (druiso (pr1 x) (pr2 x))).
  Qed.

  Lemma total_rightunitor_nat
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (druiso : disp_rightunitor_nat dru^{DM})
    : rightunitor_nat (total_rightunitordata dru^{DM}).
  Proof.
    intros x y f.
    use total2_paths_b.
    - exact ((pr1 (monoidal_rightunitorlaw M)) (pr1 x) (pr1 y) (pr1 f)).
    - exact (druiso (pr1 x) (pr1 y) (pr1 f) (pr2 x) (pr2 y) (pr2 f)).
  Defined.

  Lemma total_rightunitor_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (druiso : disp_rightunitor_law dru^{DM} druinv^{DM})
    : rightunitor_law
        (total_rightunitordata dru^{DM})
        (total_rightunitorinvdata druinv^{DM}).
  Proof.
    exact (total_rightunitor_nat (pr1 druiso),,total_rightunitor_iso_law (pr2 druiso)).
  Defined.

  Lemma total_associator_nat_leftwhisker
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dαlnat : disp_associator_nat_leftwhisker dα^{DM})
    : associator_nat_leftwhisker (total_associatordata dα^{DM}).
  Proof.
    intros x y z z' h.
    use total2_paths_b.
    - exact ((associatorlaw_natleft
                (monoidal_associatorlaw M))
               (pr1 x) (pr1 y) (pr1 z) (pr1 z')
               (pr1 h)).
    - exact (dαlnat (pr1 x) (pr1 y) (pr1 z) (pr1 z')
                    (pr1 h)
                    (pr2 x) (pr2 y) (pr2 z) (pr2 z')
                    (pr2 h)).
  Qed.

  Lemma total_associator_nat_rightwhisker
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dαrnat : disp_associator_nat_rightwhisker dα^{DM})
    : associator_nat_rightwhisker (total_associatordata dα^{DM}).
  Proof.
    intros x1 x2 y z f.
    use total2_paths_b.
    - exact ((associatorlaw_natright
                (monoidal_associatorlaw M))
               (pr1 x1) (pr1 x2) (pr1 y) (pr1 z)
               (pr1 f)).
    - exact (dαrnat (pr1 x1) (pr1 x2) (pr1 y) (pr1 z)
                    (pr1 f)
                    (pr2 x1) (pr2 x2) (pr2 y) (pr2 z)
                    (pr2 f)).
  Qed.

  Lemma total_associator_nat_leftrightwhisker
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dαlrnat : disp_associator_nat_leftrightwhisker dα^{DM})
    : associator_nat_leftrightwhisker (total_associatordata dα^{DM}).
  Proof.
    intros x y1 y2 z g.
    use total2_paths_b.
    - exact ((associatorlaw_natleftright
                (monoidal_associatorlaw M))
               (pr1 x) (pr1 y1) (pr1 y2) (pr1 z)
               (pr1 g)).
    - exact (dαlrnat (pr1 x) (pr1 y1) (pr1 y2) (pr1 z)
                     (pr1 g)
                     (pr2 x) (pr2 y1) (pr2 y2) (pr2 z)
                     (pr2 g)).
  Qed.

  Lemma total_associator_iso_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dαiso : disp_associator_iso dα^{DM} dαinv^{DM})
    : associator_iso_law
        (total_associatordata dα^{DM})
        (total_associatorinvdata dαinv^{DM}).
  Proof.
    intros x y z.
   - split.
      + use total2_paths_b.
        * exact (pr1 (associatorlaw_iso_law
                        (monoidal_associatorlaw M)
                        (pr1 x) (pr1 y) (pr1 z))).
        * exact (pr2 ((dαiso) (pr1 x) (pr1 y) (pr1 z) (pr2 x) (pr2 y) (pr2 z))).
      + use total2_paths_b.
        * exact (pr2 (associatorlaw_iso_law
                        (monoidal_associatorlaw M)
                        (pr1 x) (pr1 y) (pr1 z))).
        * exact (pr1 ((dαiso) (pr1 x) (pr1 y) (pr1 z) (pr2 x) (pr2 y) (pr2 z))).
  Qed.

  Lemma total_associator_law
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dαiso : disp_associator_law dα^{DM} dαinv^{DM})
    : associator_law
        (total_associatordata dα^{DM})
        (total_associatorinvdata dαinv^{DM}).
  Proof.
    split with (total_associator_nat_leftwhisker (disp_associatorlaw_natleft dαiso)).
    split with (total_associator_nat_rightwhisker (disp_associatorlaw_natright dαiso)).
    split with (total_associator_nat_leftrightwhisker (disp_associatorlaw_natleftright dαiso)).
    exact (total_associator_iso_law (disp_associatorlaw_iso dαiso)).
  Qed.

  Lemma total_triangleidentity
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dti : disp_triangle_identity dlu^{DM} dru^{DM} dα^{DM})
    : triangle_identity
        (total_leftunitordata dlu^{DM})
        (total_rightunitordata dru^{DM})
        (total_associatordata dα^{DM}).
  Proof.
    intros x y.
    use total2_paths_b.
    - exact ((monoidal_triangleidentity M) (pr1 x) (pr1 y)).
    - exact (dti (pr1 x) (pr1 y) (pr2 x) (pr2 y)).
  Qed.

  Lemma total_pentagonidentity
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        {DM : disp_monoidal_data D M}
        (dpi : disp_pentagon_identity dα^{DM})
    : pentagon_identity (total_associatordata dα^{DM}).
  Proof.
    intros w x y z.
    use total2_paths_b.
    - exact ((monoidal_pentagonidentity M) (pr1 w) (pr1 x) (pr1 y) (pr1 z)).
    - exact (dpi (pr1 w) (pr1 x) (pr1 y) (pr1 z) (pr2 w) (pr2 x) (pr2 y) (pr2 z)).
  Qed.

  Definition total_monoidallaws
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : monoidal_laws (total_monoidaldata DM).
  Proof.
    exists (pr2 (total_tensor DM)).
    exists (total_leftunitor_law (disp_monoidal_leftunitorlaw DM)).
    exists (total_rightunitor_law (disp_monoidal_rightunitorlaw DM)).
    exists (total_associator_law (disp_monoidal_associatorlaw DM)).
    exists (total_triangleidentity (disp_monoidal_triangleidentity DM)).
    exact (total_pentagonidentity (disp_monoidal_pentagonidentity DM)).
  Qed.

  Definition total_monoidal
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : monoidal T(D)
    := (total_monoidaldata DM,, total_monoidallaws DM).

  Notation "π^{ D }" := (pr1_category D).
  Notation "TM( DM )" := (total_monoidal DM).

  Lemma projection_preserves_unit
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_unit TM(DM) M π^{D}.
  Proof.
    apply identity.
  Defined.

  Lemma projection_preserves_tensordata
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_tensordata TM(DM) M π^{D}.
  Proof.
    intros x y.
    apply identity.
  Defined.

  Definition projection_fmonoidaldata
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : fmonoidal_data TM(DM) M π^{D}
    := (projection_preserves_tensordata DM,, projection_preserves_unit DM).

  Lemma projection_preserves_tensornatleft
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_tensor_nat_left (projection_preserves_tensordata DM).
  Proof.
    intros x y1 y2 g.
    rewrite id_left.
    apply id_right.
  Qed.

  Lemma projection_preserves_tensornatright
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_tensor_nat_right (projection_preserves_tensordata DM).
  Proof.
    intros x1 x2 y f.
    rewrite id_left.
    apply id_right.
  Qed.

  Lemma projection_preserves_leftunitality
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_leftunitality
        (projection_preserves_tensordata DM)
        (projection_preserves_unit DM).
  Proof.
    intro x.
    rewrite (bifunctor_rightid M).
    rewrite id_left.
    apply id_left.
  Qed.

  Lemma projection_preserves_rightunitality
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_rightunitality
        (projection_preserves_tensordata DM)
        (projection_preserves_unit DM).
  Proof.
    intro x.
    rewrite (bifunctor_leftid M).
    rewrite id_left.
    apply id_left.
  Qed.

  Lemma projection_preserves_associativity
        {C : category}
        {D : disp_cat C}
        {M : monoidal C}
        (DM : disp_monoidal D M)
    : preserves_associativity (projection_preserves_tensordata DM).
  Proof.
    intros x y z.
    rewrite (bifunctor_leftid M).
    rewrite id_right.
    rewrite id_right.
    rewrite (bifunctor_rightid M).
    rewrite id_left.
    rewrite id_right.
    apply idpath.
  Qed.

  Definition projection_fmonoidal_laxlaws
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : fmonoidal_laxlaws (projection_fmonoidaldata DM)
    := (projection_preserves_tensornatleft DM
        ,, projection_preserves_tensornatright DM
        ,, projection_preserves_associativity DM
        ,, projection_preserves_leftunitality DM
        ,, projection_preserves_rightunitality DM).

  Definition projection_fmonoidal_lax
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : fmonoidal_lax TM(DM) M π^{D}
    := (projection_fmonoidaldata DM,, projection_fmonoidal_laxlaws DM).

  Definition projection_preservestensor_strictly
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : preserves_tensor_strictly (projection_preserves_tensordata DM).
  Proof.
    intros x y.
    use tpair.
    - apply idpath.
    - apply idpath.
  Qed.

  Definition projection_preservesunit_strictly
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : preserves_unit_strictly (projection_preserves_unit DM).
  Proof.
    use tpair.
    - apply idpath.
    - apply idpath.
  Qed.

  Definition projection_fmonoidal
             {C : category}
             {D : disp_cat C}
             {M : monoidal C}
             (DM : disp_monoidal D M)
    : fmonoidal TM(DM) M π^{D}.
  Proof.
    exists (projection_fmonoidal_lax DM).
    split.
    - apply strictlytensorpreserving_is_strong.
      exact (projection_preservestensor_strictly DM).
    - apply strictlyunitpreserving_is_strong.
      exact (projection_preservesunit_strictly DM).
  Defined.
End MonoidalTotalCategory.