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

 Colimits in categories enriched over posets

 If we have a category enriched over posets, then we can
 characterize colimits using elementary terms. The
 characterization is similar for products: the initial object is
 inherited from the underlying category, while for coproducts and
 coequalizer, we need to demand that the arrow coming
 from the universal property is monotone.

 To construct copowers in a category `C` enriched over posets, we
 assume that we have a poset `P` and an object `x` of `C`. To
 construct the copower, we take a coproduct of `x` indexed by the
 underlying set of `P`. As such, `C` must have 'large enough'
 coproducts, because otherwise, this product cannot be constructed.

 Contents
 1. Initial object
 2. Binary coroducts
 3. Coqualizers
 4. Copowers
 5. Type indexed coproducts

 *****************************************************************)
Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.
Require Import UniMath.Combinatorics.Posets.
Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.Core.Isos.
Require Import UniMath.CategoryTheory.Core.Univalence.
Require Import UniMath.CategoryTheory.DisplayedCats.Examples.CategoryOfPosets.
Require Import UniMath.CategoryTheory.EnrichedCats.Enrichment.
Require Import UniMath.CategoryTheory.EnrichedCats.Examples.PosetEnriched.
Require Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedInitial.
Require Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedBinaryCoproducts.
Require Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCoproducts.
Require Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCoequalizers.
Require Import UniMath.CategoryTheory.EnrichedCats.Colimits.EnrichedCopowers.
Require Import UniMath.CategoryTheory.Monoidal.Categories.
Require Import UniMath.CategoryTheory.Monoidal.Structure.Symmetric.
Require Import UniMath.CategoryTheory.Monoidal.Structure.Closed.
Require Import UniMath.CategoryTheory.Monoidal.Structure.Cartesian.
Require Import UniMath.CategoryTheory.Monoidal.Examples.PosetsMonoidal.
Require Import UniMath.CategoryTheory.Monoidal.Examples.CartesianMonoidal.
Require Import UniMath.CategoryTheory.limits.terminal.
Require Import UniMath.CategoryTheory.limits.binproducts.
Require Import UniMath.CategoryTheory.limits.products.
Require Import UniMath.CategoryTheory.limits.equalizers.
Require Import UniMath.CategoryTheory.limits.initial.
Require Import UniMath.CategoryTheory.limits.bincoproducts.
Require Import UniMath.CategoryTheory.limits.coproducts.
Require Import UniMath.CategoryTheory.limits.coequalizers.

Local Open Scope cat.
Local Open Scope moncat.
Import MonoidalNotations.

Proposition isaprop_Coequalizer
            {C : category}
            (HC : is_univalent C)
            {x y : C}
            (f g : x --> y)
  : isaprop (Coequalizer f g).
Proof.
  use invproofirrelevance.
  intros φ₁ φ₂.
  use subtypePath.
  {
    intro.
    use (isaprop_total2 (_ ,, _) (λ _, (_ ,, _))).
    - apply homset_property.
    - simpl.
      repeat (use impred ; intro).
      apply isapropiscontr.
  }
  use total2_paths_f.
  - use (isotoid _ HC).
    exact (z_iso_between_Coequalizer φ₁ φ₂).
  - rewrite transportf_isotoid' ; cbn.
    apply CoequalizerCommutes.
Qed.

Section PosetEnrichmentColimits.
  Context {C : category}
          (E : poset_enrichment C).

  Let E' : enrichment C poset_sym_mon_closed_cat
    := make_enrichment_over_poset C E.

  (**
   1. Initial object
   *)
  Section PosetEnrichedInitial.
    Context {x : C}
            (Hx : isInitial C x).

    Let I : Initial C := make_Initial x Hx.

    Definition poset_enrichment_is_initial
      : is_initial_enriched E' x.
    Proof.
      use make_is_initial_enriched.
      - intros P y.
        simple refine (_ ,, _).
        + exact (λ _, InitialArrow I y).
        + abstract
            (intros x₁ x₂ p ;
             apply refl_PartialOrder).
      - abstract
          (intros P y f g ;
           use eq_monotone_function ;
           intros z ;
           apply (@InitialArrowEq _ I)).
    Defined.
  End PosetEnrichedInitial.

  Definition make_poset_enrichment_initial
             (HC : Initial C)
    : initial_enriched E'
    := pr1 HC ,, poset_enrichment_is_initial (pr2 HC).

  Definition poset_terminal_enriched_weq_Initial
             (HC : is_univalent C)
    : initial_enriched E' ≃ Initial C.
  Proof.
    use weqimplimpl.
    - exact (λ T, initial_underlying E' T).
    - exact make_poset_enrichment_initial.
    - apply (isaprop_initial_enriched _ HC).
    - apply (isaprop_Initial _ HC).
  Defined.

  (**
   2. Binary coproducts
   *)
  Definition poset_enrichment_binary_coprod
    : UU
    := ∑ (BC : BinCoproducts C),
       ∏ (x₁ x₂ y : C)
         (f f' : x₁ --> y)
         (qf : E _ _ f f')
         (g g' : x₂ --> y)
         (qg : E _ _ g g'),
       E _ _ (BinCoproductArrow (BC x₁ x₂) f g)
             (BinCoproductArrow (BC x₁ x₂) f' g').

  Proposition isaprop_poset_enrichment_binary_coprod
              (HC : is_univalent C)
    : isaprop poset_enrichment_binary_coprod.
  Proof.
    simple refine (isaprop_total2 (_ ,, _) (λ _, (_ ,, _))).
    - do 2 (use impred ; intro).
      apply (isaprop_BinCoproduct _ HC).
    - repeat (use impred ; intro).
      apply propproperty.
  Qed.

  Section PosetEnrichedCoprodAccessors.
    Context (EBC : poset_enrichment_binary_coprod).

    Definition poset_enrichment_obj_binary_coprod
               (x y : C)
      : C
      := pr1 EBC x y.

    Definition poset_enrichment_obj_in1
               (x y : C)
      : x --> poset_enrichment_obj_binary_coprod x y
      := BinCoproductIn1 (pr1 EBC x y).

    Definition poset_enrichment_obj_in2
               (x y : C)
      : y --> poset_enrichment_obj_binary_coprod x y
      := BinCoproductIn2 (pr1 EBC x y).

    Definition poset_enrichment_obj_sum
               {z x y : C}
               (f : x --> z)
               (g : y --> z)
      : poset_enrichment_obj_binary_coprod x y --> z
      := BinCoproductArrow (pr1 EBC x y) f g.

    Proposition poset_enrichment_obj_in1_sum
                {z x y : C}
                (f : x --> z)
                (g : y --> z)
      : poset_enrichment_obj_in1 x y · poset_enrichment_obj_sum f g
        =
        f.
    Proof.
      apply BinCoproductIn1Commutes.
    Qed.

    Proposition poset_enrichment_obj_in2_sum
                {z x y : C}
                (f : x --> z)
                (g : y --> z)
      : poset_enrichment_obj_in2 x y · poset_enrichment_obj_sum f g
        =
        g.
    Proof.
      apply BinCoproductIn2Commutes.
    Qed.

    Proposition poset_enrichment_binary_coprod_arr_eq
                {w x y : C}
                {f g : poset_enrichment_obj_binary_coprod x y --> w}
                (p : poset_enrichment_obj_in1 x y · f
                     =
                     poset_enrichment_obj_in1 x y · g)
                (q : poset_enrichment_obj_in2 x y · f
                     =
                     poset_enrichment_obj_in2 x y · g)
      : f = g.
    Proof.
      use (BinCoproductArrowsEq _ _ _ (pr1 EBC x y)).
      - exact p.
      - exact q.
    Qed.

    Definition poset_enrichment_binary_coprod_pair
               (x y z : C)
      : E' ⦃ x , z ⦄ ⊗ (E' ⦃ y , z ⦄) --> E' ⦃ poset_enrichment_obj_binary_coprod x y , z ⦄.
    Proof.
      simple refine (_ ,, _).
      - exact (λ fg, poset_enrichment_obj_sum (pr1 fg) (pr2 fg)).
      - intros fg₁ fg₂ p.
        apply (pr2 EBC).
        + exact (pr1 p).
        + exact (pr2 p).
    Defined.
  End PosetEnrichedCoprodAccessors.

  Section PosetCoprod.
    Context (EBC : poset_enrichment_binary_coprod)
            (x y : C).

    Definition make_poset_enriched_binary_coprod_cocone
      : enriched_binary_coprod_cocone E' x y.
    Proof.
      use make_enriched_binary_coprod_cocone.
      - exact (poset_enrichment_obj_binary_coprod EBC x y).
      - exact (enriched_from_arr E' (poset_enrichment_obj_in1 EBC x y)).
      - exact (enriched_from_arr E' (poset_enrichment_obj_in2 EBC x y)).
    Defined.

    Definition poset_enrichment_binary_coprod_is_coprod
      : is_binary_coprod_enriched E' x y make_poset_enriched_binary_coprod_cocone.
    Proof.
      use make_is_binary_coprod_enriched.
      - intros z P f g.
        refine (_ · poset_enrichment_binary_coprod_pair _ _ _ _).
        simple refine (_ ,, _).
        + exact (prodtofuntoprod (pr1 f ,, pr1 g)).
        + apply prodtofun_is_monotone.
          * exact (pr2 f).
          * exact (pr2 g).
      - abstract
          (intros z P f g ;
           use eq_monotone_function ;
           intros w ; cbn ;
           apply poset_enrichment_obj_in1_sum).
      - abstract
          (intros z P f g ;
           use eq_monotone_function ;
           intros w ; cbn ;
           apply poset_enrichment_obj_in2_sum).
      - abstract
          (intros z P φ₁ φ₂ q₁ q₂ ;
           use eq_monotone_function ;
           intro w ;
           use poset_enrichment_binary_coprod_arr_eq ;
           [ exact (eqtohomot (maponpaths (λ f, pr1 f) q₁) w)
           | exact (eqtohomot (maponpaths (λ f, pr1 f) q₂) w) ]).
    Defined.
  End PosetCoprod.

  Definition make_poset_enrichment_binary_coprod
             (EBC : poset_enrichment_binary_coprod)
    : enrichment_binary_coprod E'
    := λ x y,
       make_poset_enriched_binary_coprod_cocone EBC x y
       ,,
       poset_enrichment_binary_coprod_is_coprod EBC x y.

  Section ToPosetCoproduct.
    Context (EP : enrichment_binary_coprod E')
            {x₁ x₂ y : C}.

    Let prod : poset_sym_mon_closed_cat
      := (E' ⦃ x₁ , y ⦄) ⊗ (E' ⦃ x₂ , y ⦄).

    Let prod_pr1 : prod --> E' ⦃ x₁ , y ⦄
      := _ ,, dirprod_pr1_is_monotone _ _.

    Let prod_pr2 : prod --> E' ⦃ x₂ , y ⦄
      := _ ,, dirprod_pr2_is_monotone _ _.

    Definition poset_to_underlying_binary_coprod_map
               (f : x₁ --> y)
               (g : x₂ --> y)
      : underlying_BinCoproduct E' x₁ x₂ (pr2 (EP x₁ x₂)) --> y
      := pr1 (BinProductArrow
                category_of_posets
                (is_binary_coprod_enriched_to_BinProduct E' _ _ (pr2 (EP x₁ x₂)) y)
                prod_pr1
                prod_pr2)
             (f ,, g).

    Proposition poset_to_underlying_binary_coprod_map_in1
                (f : x₁ --> y)
                (g : x₂ --> y)
      : enriched_coprod_cocone_in1 E' x₁ x₂ (pr1 (EP x₁ x₂))
        · poset_to_underlying_binary_coprod_map f g
        =
        f.
    Proof.
      exact (eqtohomot
               (maponpaths
                  pr1
                  (BinProductPr1Commutes
                     category_of_posets
                     _ _
                     (is_binary_coprod_enriched_to_BinProduct E' _ _ (pr2 (EP x₁ x₂)) y)
                     _
                     prod_pr1
                     prod_pr2))
               (f ,, g)).
    Qed.

    Proposition poset_to_underlying_binary_coprod_map_in2
                (f : x₁ --> y)
                (g : x₂ --> y)
      : enriched_coprod_cocone_in2 E' x₁ x₂ (pr1 (EP x₁ x₂))
        · poset_to_underlying_binary_coprod_map f g
        =
        g.
    Proof.
      exact (eqtohomot
               (maponpaths
                  pr1
                  (BinProductPr2Commutes
                     category_of_posets
                     _ _
                     (is_binary_coprod_enriched_to_BinProduct E' _ _ (pr2 (EP x₁ x₂)) y)
                     _
                     prod_pr1
                     prod_pr2))
               (f ,, g)).
    Qed.

    Proposition poset_to_underlying_binary_coprod_map_monotone
                {φ₁ φ₂ : x₁ --> y}
                {ψ₁ ψ₂ : x₂ --> y}
                (p : E x₁ y φ₁ φ₂)
                (q : E x₂ y ψ₁ ψ₂)
      : E _ _ (poset_to_underlying_binary_coprod_map φ₁ ψ₁)
              (poset_to_underlying_binary_coprod_map φ₂ ψ₂).
    Proof.
      exact (pr2 (@BinProductArrow
                    _ _ _
                    (is_binary_coprod_enriched_to_BinProduct E' _ _ (pr2 (EP x₁ x₂)) y)
                    prod
                    prod_pr1
                    prod_pr2)
                 (φ₁ ,, ψ₁)
                 (φ₂ ,, ψ₂)
                 (p ,, q)).
    Qed.

    Proposition poset_to_underlying_binary_coprod_map_eq
                (f : x₁ --> y)
                (g : x₂ --> y)
      : BinCoproductArrow (underlying_BinCoproduct E' x₁ x₂ (pr2 (EP x₁ x₂))) f g
        =
        poset_to_underlying_binary_coprod_map f g.
    Proof.
      use is_binary_coprod_enriched_arrow_eq.
      - exact (pr2 (EP x₁ x₂)).
      - refine (_ @ !(poset_to_underlying_binary_coprod_map_in1 f g)).
        apply (BinCoproductIn1Commutes
                 C
                 _ _
                 (underlying_BinCoproduct E' x₁ x₂ (pr2 (EP x₁ x₂)))
                 _
                 f g).
      - refine (_ @ !(poset_to_underlying_binary_coprod_map_in2 f g)).
        apply (BinCoproductIn2Commutes
                 C
                 _ _
                 (underlying_BinCoproduct E' x₁ x₂ (pr2 (EP x₁ x₂)))
                 _
                 f g).
    Qed.
  End ToPosetCoproduct.

  Definition to_poset_enrichment_binary_coprod
             (EP : enrichment_binary_coprod E')
    : poset_enrichment_binary_coprod.
  Proof.
    simple refine (_ ,, _).
    - exact (λ x y, underlying_BinCoproduct E' x y (pr2 (EP x y))).
    - abstract
        (intros x y₁ y₂ f f' p g g' q ;
         rewrite !poset_to_underlying_binary_coprod_map_eq ;
         apply (poset_to_underlying_binary_coprod_map_monotone EP p q)).
  Defined.

  Definition poset_enrichment_coprod_weq
             (HC : is_univalent C)
    : enrichment_binary_coprod E' ≃ poset_enrichment_binary_coprod.
  Proof.
    use weqimplimpl.
    - apply to_poset_enrichment_binary_coprod.
    - apply make_poset_enrichment_binary_coprod.
    - apply (isaprop_enrichment_binary_coprod HC).
    - apply (isaprop_poset_enrichment_binary_coprod HC).
  Defined.

  (**
   3. Coequalizers
   *)
  Definition poset_enrichment_coequalizers
    : UU
    := ∑ (EC : Coequalizers C),
       ∏ (x y z : C)
         (f g : x --> y)
         (h₁ h₂ : y --> z)
         (p₁ : f · h₁ = g · h₁)
         (p₂ : f · h₂ = g · h₂)
         (qh : E _ _ h₁ h₂),
       E _ _ (CoequalizerOut (EC x y f g) z h₁ p₁)
             (CoequalizerOut (EC x y f g) z h₂ p₂).

  Proposition isaprop_poset_enrichment_coequalizers
              (HC : is_univalent C)
    : isaprop poset_enrichment_coequalizers.
  Proof.
    simple refine (isaprop_total2 (_ ,, _) (λ _, (_ ,, _))).
    - repeat (use impred ; intro).
      apply isaprop_Coequalizer.
      exact HC.
    - repeat (use impred ; intro).
      apply propproperty.
  Qed.

  Section PosetEnrichedCoequalizerAccessors.
    Context (EEC : poset_enrichment_coequalizers).

    Definition poset_enrichment_obj_coequalizer
               {x y : C}
               (f g : x --> y)
      : C
      := pr1 EEC x y f g.

    Definition poset_enrichment_obj_coeq_in
               {x y : C}
               (f g : x --> y)
      : y --> poset_enrichment_obj_coequalizer f g
      := CoequalizerArrow (pr1 EEC x y f g).

    Proposition poset_enrichment_obj_coeq_in_eq
                {x y : C}
                (f g : x --> y)
      : f · poset_enrichment_obj_coeq_in f g
        =
        g · poset_enrichment_obj_coeq_in f g.
    Proof.
      apply CoequalizerEqAr.
    Qed.

    Definition poset_enrichment_obj_from_coequalizer
               {x y z : C}
               {f g : x --> y}
               (h : y --> z)
               (q : f · h = g · h)
      : poset_enrichment_obj_coequalizer f g --> z
      := CoequalizerOut (pr1 EEC x y f g) z h q.

    Proposition poset_enrichment_obj_from_coequalizer_in
                {x y z : C}
                {f g : x --> y}
                (h : y --> z)
                (q : f · h = g · h)
      : poset_enrichment_obj_coeq_in f g · poset_enrichment_obj_from_coequalizer h q
        =
        h.
    Proof.
      apply CoequalizerCommutes.
    Qed.

    Proposition poset_enrichment_coequalizer_arr_eq
                {x y z : C}
                {f g : x --> y}
                {h₁ h₂ : poset_enrichment_obj_coequalizer f g --> z}
                (q : poset_enrichment_obj_coeq_in f g · h₁
                     =
                     poset_enrichment_obj_coeq_in f g · h₂)
      : h₁ = h₂.
    Proof.
      use CoequalizerOutsEq.
      exact q.
    Qed.

    Definition poset_enrichment_coequalizer_to_equalizer
               {x y z : C}
               (f g : x --> y)
      : Equalizers_category_of_posets
          _
          _
          (precomp_arr E' z f)
          (precomp_arr E' z g)
        -->
        E' ⦃ poset_enrichment_obj_coequalizer f g , z ⦄.
    Proof.
      simple refine (_ ,, _).
      - cbn.
        exact (λ hp, poset_enrichment_obj_from_coequalizer (pr1 hp) (pr2 hp)).
      - intros h₁ h₂ q.
        exact (pr2 EEC x y z f g (pr1 h₁) (pr1 h₂) (pr2 h₁) (pr2 h₂) q).
    Defined.
  End PosetEnrichedCoequalizerAccessors.

  Section PosetCoequalizer.
    Context (EEC : poset_enrichment_coequalizers)
            {x y : C}
            (f g : x --> y).

    Definition make_poset_enrichment_coequalizer_cocone
      : enriched_coequalizer_cocone E' f g.
    Proof.
      use make_enriched_coequalizer_cocone.
      - exact (poset_enrichment_obj_coequalizer EEC f g).
      - exact (enriched_from_arr E' (poset_enrichment_obj_coeq_in EEC f g)).
      - exact (poset_enrichment_obj_coeq_in_eq EEC f g).
    Defined.

    Definition make_poset_enrichment_coequalizer_is_coequalizer
      : is_coequalizer_enriched
          E'
          f g
          make_poset_enrichment_coequalizer_cocone.
    Proof.
      use make_is_coequalizer_enriched.
      - abstract
          (intros w P φ₁ φ₂ q ;
           use eq_monotone_function ;
           intro z ;
           use poset_enrichment_coequalizer_arr_eq ;
           exact (eqtohomot (maponpaths pr1 q) z)).
      - intros w P h q.
        refine (_ · poset_enrichment_coequalizer_to_equalizer EEC f g).
        simple refine (_ ,, _).
        + refine (λ z, pr1 h z ,, _).
          exact (eqtohomot (maponpaths pr1 q) z).
        + abstract
            (apply Equalizer_map_monotone ;
             apply (pr2 h)).
      - abstract
          (intros w P h q ;
           use eq_monotone_function ;
           intros z ;
           apply poset_enrichment_obj_from_coequalizer_in).
    Defined.
  End PosetCoequalizer.

  Definition make_poset_enrichment_coequalizers
             (EEC : poset_enrichment_coequalizers)
    : enrichment_coequalizers E'.
  Proof.
    intros x y f g.
    simple refine (_ ,, _).
    - exact (make_poset_enrichment_coequalizer_cocone EEC f g).
    - exact (make_poset_enrichment_coequalizer_is_coequalizer EEC f g).
  Defined.

  Section ToPosetCoequalizer.
    Context (EEC : enrichment_coequalizers E')
            {x y z : C}
            (f g : x --> y).

    Let Eq : Equalizer _ _
      := Equalizers_category_of_posets
           _
           _
           (precomp_arr E' z f)
           (precomp_arr E' z g).

    Let Eq_pr : Eq --> E' ⦃ y , z ⦄
      := EqualizerArrow _.

    Let Eq_path : Eq_pr · precomp_arr E' z f
                  =
                  Eq_pr · precomp_arr E' z g
      := EqualizerEqAr _.

    Definition poset_to_underlying_coequalizer_map
               (h : y --> z)
               (q : f · h = g · h)
      : underlying_Coequalizer E' f g (pr2 (EEC x y f g)) --> z
      := pr1 (EqualizerIn
                (is_coequalizer_enriched_to_Equalizer E' f g (pr2 (EEC x y f g)) z)
                Eq
                Eq_pr
                Eq_path)
              (h ,, q).

    Proposition poset_to_underlying_coequalizer_map_in
                (h : y --> z)
                (q : f · h = g · h)
      : enriched_coequalizer_cocone_in E' f g (pr1 (EEC x y f g))
        · poset_to_underlying_coequalizer_map h q
        =
        h.
    Proof.
      exact (eqtohomot
               (maponpaths
                  pr1
                  (EqualizerCommutes
                     (is_coequalizer_enriched_to_Equalizer E' f g (pr2 (EEC x y f g)) z)
                     Eq
                     Eq_pr
                     Eq_path))
               (h ,, q)).
    Qed.

    Proposition poset_to_underlying_coequalizer_map_monotone
                (h₁ h₂ : y --> z)
                (q₁ : f · h₁ = g · h₁)
                (q₂ : f · h₂ = g · h₂)
                (ph : E y z h₁ h₂)
      : E _ _ (poset_to_underlying_coequalizer_map h₁ q₁)
              (poset_to_underlying_coequalizer_map h₂ q₂).
    Proof.
      apply (pr2 (EqualizerIn
                    (is_coequalizer_enriched_to_Equalizer E' f g (pr2 (EEC x y f g)) z)
                    Eq
                    Eq_pr
                    Eq_path)
               (h₁ ,, q₁)
               (h₂ ,, q₂)
               ph).
    Qed.

    Proposition poset_to_underlying_coequalizer_map_eq
                (h : y --> z)
                (q : f · h = g · h)
      : CoequalizerOut (underlying_Coequalizer E' f g (pr2 (EEC x y f g))) z h q
        =
        poset_to_underlying_coequalizer_map h q.
    Proof.
      use underlying_Coequalizer_arr_eq.
      {
        exact (pr2 (EEC x y f g)).
      }
      etrans.
      {
        apply (CoequalizerCommutes (underlying_Coequalizer E' f g (pr2 (EEC x y f g)))).
      }
      refine (!_).
      apply poset_to_underlying_coequalizer_map_in.
    Qed.
  End ToPosetCoequalizer.

  Definition to_poset_enrichment_coequalizer
             (EEC : enrichment_coequalizers E')
    : poset_enrichment_coequalizers.
  Proof.
    simple refine (_ ,, _).
    - exact (λ x y f g, underlying_Coequalizer E' f g (pr2 (EEC x y f g))).
    - abstract
        (intros w x y f g h₁ h₂ p₁ p₂ qh ;
         rewrite !poset_to_underlying_coequalizer_map_eq ;
         apply poset_to_underlying_coequalizer_map_monotone ;
         exact qh).
  Defined.

  Definition poset_enrichment_coequalizer_weq
             (HC : is_univalent C)
    : enrichment_coequalizers E' ≃ poset_enrichment_coequalizers.
  Proof.
    use weqimplimpl.
    - apply to_poset_enrichment_coequalizer.
    - apply make_poset_enrichment_coequalizers.
    - apply (isaprop_enrichment_coequalizers HC).
    - apply (isaprop_poset_enrichment_coequalizers HC).
  Defined.

  (**
   4. Copowers
   *)
  Definition poset_enrichment_copows
    : UU
    := ∑ (coprods : ∏ (P : poset_sym_mon_closed_cat), Coproducts (pr11 P) C),
       ∏ (P : poset_sym_mon_closed_cat)
         (x : C),
       is_monotone
         (pr2 P)
         (E x (coprods P (λ _, x)))
         (CoproductIn _ _ (coprods P (λ _, x)))
       ×
       (∏ (y : C),
        is_monotone
          (monotone_function_PartialOrder
             (pr2 P)
             (E x y))
          (E (coprods P (λ _, x)) y)
          (λ f, CoproductArrow _ _ (coprods P (λ _, x)) (pr1 f))).

  Section PosetEnrichmentCopowersAccessors.
    Context (HE : poset_enrichment_copows).

    Definition poset_copows_coprod
               (P : poset_sym_mon_closed_cat)
               (x : C)
      : Coproduct (pr11 P) C (λ _, x)
      := pr1 HE P (λ _, x).

    Definition poset_copows_in
               {P : poset_sym_mon_closed_cat}
               {x : C}
               (i : pr11 P)
      : x --> poset_copows_coprod P x
      := CoproductIn _ _ (poset_copows_coprod P x) i.

    Proposition poset_copows_monotone_in
                (P : poset_sym_mon_closed_cat)
                (x : C)
      : is_monotone
          (pr2 P)
          (E x (poset_copows_coprod P x))
          poset_copows_in.
    Proof.
      exact (pr1 (pr2 HE P x)).
    Qed.

    Proposition poset_copows_monotone_coproduct_arr
                (P : poset_sym_mon_closed_cat)
                (x y : C)
      : is_monotone
          (monotone_function_PartialOrder
             (pr2 P)
             (E x y))
          (E (poset_copows_coprod P x) y)
          (λ f, CoproductArrow _ _ (poset_copows_coprod P x) (pr1 f)).
    Proof.
      exact (pr2 (pr2 HE P x) y).
    Qed.
  End PosetEnrichmentCopowersAccessors.

  Section PosetEnrichmentCopowers.
    Context (HE : poset_enrichment_copows)
            (P : poset_sym_mon_closed_cat)
            (x : C).

    Let copow : Coproduct _ C (λ _, x) := poset_copows_coprod HE P x.
    Let copow_in : ∏ (_ : pr11 P), x --> copow := λ i, poset_copows_in HE i.

    Definition poset_copower_cocone
      : copower_cocone E' P x.
    Proof.
      simple refine (_ ,, _).
      - exact copow.
      - simple refine (_ ,, _).
        + exact copow_in.
        + exact (poset_copows_monotone_in HE P x).
    Defined.

    Definition poset_copower_map
               (y : C)
      : P ⊸ (E' ⦃ x , y ⦄) --> E' ⦃ poset_copower_cocone , y ⦄.
    Proof.
      simple refine (_ ,, _).
      - intro f.
        exact (CoproductArrow _ _ copow (pr1 f)).
      - exact (poset_copows_monotone_coproduct_arr HE P x y).
    Defined.

    Definition poset_copower_is_copower
      : is_copower_enriched E' P x poset_copower_cocone.
    Proof.
      use make_is_copower_enriched.
      - exact poset_copower_map.
      - abstract
          (intro y ;
           use eq_monotone_function ;
           intro f ;
           cbn in f ;
           use CoproductArrow_eq ;
           intro i ;
           apply (CoproductInCommutes _ _ _ copow)).
      - abstract
          (intro y ;
           use eq_monotone_function ;
           intro f ;
           use eq_monotone_function ;
           intro i ;
           cbn ;
           apply (CoproductInCommutes _ _ _ copow)).
    Defined.
  End PosetEnrichmentCopowers.

  Definition poset_enrichment_copowers_from_coproducts
             (HE : poset_enrichment_copows)
    : enrichment_copower E'.
  Proof.
    intros P x.
    simple refine (_ ,, _).
    - exact (poset_copower_cocone HE P x).
    - apply poset_copower_is_copower.
  Defined.

  (**
   5. Type indexed coproducts
   *)
  Section TypeIndexedCoproducts.
    Context (J : UU).

    Definition poset_enrichment_coprod
      : UU
      := ∑ (PC : Coproducts J C),
         ∏ (x : C)
           (ys : J → C)
           (fs₁ : ∏ (j : J), ys j --> x)
           (fs₂ : ∏ (j : J), ys j --> x)
           (q : ∏ (j : J), E _ _ (fs₁ j) (fs₂ j)),
         E _ _ (CoproductArrow _ _ (PC ys) fs₁)
               (CoproductArrow _ _ (PC ys) fs₂).

    Proposition isaprop_poset_enrichment_coprod
                (HC : is_univalent C)
      : isaprop poset_enrichment_coprod.
    Proof.
      simple refine (isaprop_total2 (_ ,, _) (λ _, (_ ,, _))).
      - repeat (use impred ; intro).
        apply isaprop_Coproduct.
        exact HC.
      - repeat (use impred ; intro).
        apply propproperty.
    Qed.

    Section PosetEnrichedCoprodAccessors.
      Context (EC : poset_enrichment_coprod).

      Definition poset_enrichment_obj_coprod
                 (ys : J → C)
        : C
        := pr1 EC ys.

      Definition poset_enrichment_obj_coprod_in
                 (ys : J → C)
                 (j : J)
        : ys j --> poset_enrichment_obj_coprod ys
        := CoproductIn _ _ (pr1 EC ys) j.

      Definition poset_enrichment_obj_coprod_sum
                 {x : C}
                 {ys : J → C}
                 (fs : ∏ (j : J), ys j --> x)
        : poset_enrichment_obj_coprod ys --> x
        := CoproductArrow _ _ (pr1 EC ys) fs.

      Proposition poset_enrichment_obj_coprod_in_sum
                  {x : C}
                  {ys : J → C}
                  (fs : ∏ (j : J), ys j --> x)
                  (j : J)
        : poset_enrichment_obj_coprod_in ys j · poset_enrichment_obj_coprod_sum fs
          =
          fs j.
      Proof.
        apply CoproductInCommutes.
      Qed.

      Proposition poset_enrichment_coprod_arr_eq
                  {x : C}
                  {ys : J → C}
                  {f g : poset_enrichment_obj_coprod ys --> x}
                  (p : ∏ (j : J),
                       poset_enrichment_obj_coprod_in ys j · f
                       =
                       poset_enrichment_obj_coprod_in ys j · g)
        : f = g.
      Proof.
        use (CoproductArrow_eq _ _ _ (pr1 EC ys)).
        exact p.
      Qed.

      Definition poset_enrichment_coprod_pair
                 (x : C)
                 (ys : J → C)
        : Products_category_of_posets J (λ j, E' ⦃ ys j , x ⦄)
          -->
          E' ⦃ poset_enrichment_obj_coprod ys , x ⦄.
      Proof.
        simple refine (_ ,, _).
        - exact (λ fs, poset_enrichment_obj_coprod_sum (λ j, fs j)).
        - intros fs₁ fs₂ p.
          apply (pr2 EC).
          exact p.
      Defined.
    End PosetEnrichedCoprodAccessors.

    Section PosetCoprod.
      Context (EC : poset_enrichment_coprod)
              (ys : J → C).

      Definition make_poset_enriched_coprod_cocone
        : enriched_coprod_cocone E' ys.
      Proof.
        use make_enriched_coprod_cocone.
        - exact (poset_enrichment_obj_coprod EC ys).
        - exact (λ j, enriched_from_arr E' (poset_enrichment_obj_coprod_in EC ys j)).
      Defined.

      Definition poset_enrichment_coprod_is_coprod
        : is_coprod_enriched E' ys make_poset_enriched_coprod_cocone.
      Proof.
        use make_is_coprod_enriched.
        - intros z P fs.
          refine (_ · poset_enrichment_coprod_pair _ _ _).
          simple refine (_ ,, _).
          + exact (λ x j, pr1 (fs j) x).
          + abstract
              (use is_monotone_depfunction_poset_pair ;
               intro j ;
               exact (pr2 (fs j))).
        - abstract
            (intros z P f g ;
             use eq_monotone_function ;
             intros w ; cbn ;
             apply poset_enrichment_obj_coprod_in_sum).
        - abstract
            (intros z P φ₁ φ₂ q ;
             use eq_monotone_function ;
             intro w ;
             use poset_enrichment_coprod_arr_eq ;
             intro j ;
             exact (eqtohomot (maponpaths (λ f, pr1 f) (q j)) w)).
      Defined.
    End PosetCoprod.

    Definition make_poset_enrichment_coprod
               (EC : poset_enrichment_coprod)
      : enrichment_coprod E' J
      := λ ys,
         make_poset_enriched_coprod_cocone EC ys
         ,,
         poset_enrichment_coprod_is_coprod EC ys.

    Section ToPosetCoproduct.
      Context (EP : enrichment_coprod E' J)
              {x : C}
              (ys : J → C).

      Let prod : poset_sym_mon_closed_cat
        := Products_category_of_posets J (λ j, E' ⦃ ys j , x ⦄).

      Let prod_pr : ∏ (j : J), prod --> E' ⦃ ys j , x ⦄
          := λ j, _ ,, is_monotone_depfunction_poset_pr _ _ _.

      Definition poset_to_underlying_coprod_map
                 (fs : ∏ (j : J), ys j --> x)
        : underlying_Coproduct E' ys (pr2 (EP ys)) --> x
        := pr1 (ProductArrow
                  J
                  category_of_posets
                  (is_coprod_enriched_to_Product E' _ (pr2 (EP ys)) x)
                  prod_pr)
             fs.

      Proposition poset_to_underlying_coprod_map_pr
                  (fs : ∏ (j : J), ys j --> x)
                  (j : J)
        : enriched_coprod_cocone_in E' ys (pr1 (EP ys)) j
          · poset_to_underlying_coprod_map fs
          =
          fs j.
      Proof.
        exact (eqtohomot
                 (maponpaths
                    pr1
                    (ProductPrCommutes
                       J category_of_posets _
                       (is_coprod_enriched_to_Product E' _ (pr2 (EP ys)) x)
                       _
                       prod_pr
                       j))
                 fs).
      Qed.

      Proposition poset_to_underlying_coprod_map_monotone
                  {φ ψ : ∏ (j : J), ys j --> x}
                  (p : ∏ (j : J), E (ys j) x (φ j) (ψ j))
        : E _ _ (poset_to_underlying_coprod_map φ)
                (poset_to_underlying_coprod_map ψ).
      Proof.
        exact (pr2 (@ProductArrow
                      _ _ _
                      (is_coprod_enriched_to_Product E' _ (pr2 (EP ys)) x)
                      prod
                      prod_pr)
                 φ
                 ψ
                 p).
      Qed.

      Proposition poset_to_underlying_coprod_map_eq
                  (fs : ∏ (j : J), ys j --> x)
        : CoproductArrow _ C (underlying_Coproduct E' ys (pr2 (EP ys))) fs
          =
          poset_to_underlying_coprod_map fs.
      Proof.
        use is_coprod_enriched_arrow_eq.
        - exact (pr2 (EP ys)).
        - intro j.
          refine (_ @ !(poset_to_underlying_coprod_map_pr fs j)).
          apply (CoproductInCommutes
                   _ C
                   _
                   (underlying_Coproduct E' ys (pr2 (EP ys)))
                   _
                   fs).
      Qed.
    End ToPosetCoproduct.

    Definition to_poset_enrichment_coprod
               (EP : enrichment_coprod E' J)
      : poset_enrichment_coprod.
    Proof.
      simple refine (_ ,, _).
      - exact (λ ys, underlying_Coproduct E' ys (pr2 (EP ys))).
      - abstract
          (intros x ys fs₁ fs₂ p ;
           rewrite !poset_to_underlying_coprod_map_eq ;
           apply (poset_to_underlying_coprod_map_monotone EP _ p)).
    Defined.

    Definition poset_enrichment_prod_weq
               (HC : is_univalent C)
      : enrichment_coprod E' J ≃ poset_enrichment_coprod.
    Proof.
      use weqimplimpl.
      - apply to_poset_enrichment_coprod.
      - apply make_poset_enrichment_coprod.
      - apply (isaprop_enrichment_coprod HC).
      - apply (isaprop_poset_enrichment_coprod HC).
    Defined.
  End TypeIndexedCoproducts.
End PosetEnrichmentColimits.


Variable Term : Prop.
Variable R : Term -> Term -> Prop.
Variable succ : Term -> Term.
Variable alt : Term -> Term -> Term.

Axiom rel1 : forall c d e, R (alt c (succ d)) (alt (succ c) e).
Axiom rel2 : forall c d e, R (alt (succ c) d) (alt c (succ d)).

Axiom relanti : forall c d, R c d -> R d c -> False.
Axiom reltrans : forall c d e, R c d -> R d e -> R c e.

Theorem relbot : forall a b : Term, False.
Proof.
  intros.
  apply (relanti (alt (succ a) b) (alt a (succ b))).
  eapply rel2.
  eapply rel1.
Defined.


Record Preorder (A:Type) : Type := preorder
    {   rel : A -> A -> Prop
    ;   proof_refl : forall x:A, rel x x
    ;   proof_trans: forall x y z:A, rel x y -> rel y z -> rel x z
    }
    .

Arguments preorder {A} _ _ _.
Arguments rel {A} _ _ _.
Arguments proof_refl {A} _ _.
Arguments proof_trans {A} _ _ _ _ _ _.

Lemma eq_rel : forall (A:Type) (p:Preorder A), forall (x x' y y':A),
    x = x' -> y = y' -> rel p x y = rel p x' y'.
Proof.
    intros A p x x' y y' Exx Eyy. rewrite Exx, Eyy. reflexivity.
Qed.


(** * Hoare2: Hoare Logic, Part II *)

Require Export Hoare.

(* ####################################################### *)
(** * Decorated Programs *)

(** The beauty of Hoare Logic is that it is _compositional_ --
    the structure of proofs exactly follows the structure of programs.
    This suggests that we can record the essential ideas of a proof
    informally (leaving out some low-level calculational details) by
    decorating programs with appropriate assertions around each
    statement.  Such a _decorated program_ carries with it
    an (informal) proof of its own correctness. *)

(** For example, here is a complete decorated program: *)
(**
      {{ True }} ->>
      {{ m = m }}
    X ::= m;;
      {{ X = m }} ->>
      {{ X = m /\ p = p }}
    Z ::= p;
      {{ X = m /\ Z = p }} ->>
      {{ Z - X = p - m }}
    WHILE X <> 0 DO
        {{ Z - X = p - m /\ X <> 0 }} ->>
        {{ (Z - 1) - (X - 1) = p - m }}
      Z ::= Z - 1;;
        {{ Z - (X - 1) = p - m }}
      X ::= X - 1
        {{ Z - X = p - m }}
    END;
      {{ Z - X = p - m /\ ~ (X <> 0) }} ->>
      {{ Z = p - m }}
*)

(** Concretely, a decorated program consists of the program text
    interleaved with assertions.  To check that a decorated program
    represents a valid proof, we check that each individual command is
    _locally consistent_ with its accompanying assertions in the
    following sense: *)

(**
    - [SKIP] is locally consistent if its precondition and
      postcondition are the same:
          {{ P }}
          SKIP
          {{ P }}
*)

(**
    - The sequential composition of [c1] and [c2] is locally
      consistent (with respect to assertions [P] and [R]) if [c1] is
      locally consistent (with respect to [P] and [Q]) and [c2] is
      locally consistent (with respect to [Q] and [R]):
          {{ P }}
          c1;;
          {{ Q }}
          c2
          {{ R }}
*)

(**

    - An assignment is locally consistent if its precondition is
      the appropriate substitution of its postcondition:
          {{ P [X |-> a] }}
          X ::= a
          {{ P }}
*)

(**
    - A conditional is locally consistent (with respect to assertions
      [P] and [Q]) if the assertions at the top of its "then" and
      "else" branches are exactly [P /\ b] and [P /\ ~b] and if its "then"
      branch is locally consistent (with respect to [P /\ b] and [Q])
      and its "else" branch is locally consistent (with respect to
      [P /\ ~b] and [Q]):
          {{ P }}
          IFB b THEN
            {{ P /\ b }}
            c1
            {{ Q }}
          ELSE
            {{ P /\ ~b }}
            c2
            {{ Q }}
          FI
          {{ Q }}
*)

(**

    - A while loop with precondition [P] is locally consistent if its
      postcondition is [P /\ ~b] and if the pre- and postconditions of
      its body are exactly [P /\ b] and [P]:
          {{ P }}
          WHILE b DO
            {{ P /\ b }}
            c1
            {{ P }}
          END
          {{ P /\ ~b }}
*)

(**

    - A pair of assertions separated by [->>] is locally consistent if
      the first implies the second (in all states):
          {{ P }} ->>
          {{ P' }}

      This corresponds to the application of [hoare_consequence] and
      is the only place in a decorated program where checking if
      decorations are correct is not fully mechanical and syntactic,
      but involves logical and/or arithmetic reasoning.
*)

(** We have seen above how _verifying_ the correctness of a
    given proof involves checking that every single command is locally
    consistent with the accompanying assertions.  If we are instead
    interested in _finding_ a proof for a given specification we need
    to discover the right assertions. This can be done in an almost
    automatic way, with the exception of finding loop invariants,
    which is the subject of in the next section.  In the reminder of
    this section we explain in detail how to construct decorations for
    several simple programs that don't involve non-trivial loop
    invariants. *)

(* ####################################################### *)
(** ** Example: Swapping Using Addition and Subtraction *)

(** Here is a program that swaps the values of two variables using
    addition and subtraction (instead of by assigning to a temporary
    variable).
  X ::= X + Y;;
  Y ::= X - Y;;
  X ::= X - Y
    We can prove using decorations that this program is correct --
    i.e., it always swaps the values of variables [X] and [Y]. *)

(**
 (1)     {{ X = m /\ Y = n }} ->>
 (2)     {{ (X + Y) - ((X + Y) - Y) = n /\ (X + Y) - Y = m }}
        X ::= X + Y;;
 (3)     {{ X - (X - Y) = n /\ X - Y = m }}
        Y ::= X - Y;;
 (4)     {{ X - Y = n /\ Y = m }}
        X ::= X - Y
 (5)     {{ X = n /\ Y = m }}
    The decorations were constructed as follows:
      - We begin with the undecorated program (the unnumbered lines).
      - We then add the specification -- i.e., the outer
        precondition (1) and postcondition (5). In the precondition we
        use auxiliary variables (parameters) [m] and [n] to remember
        the initial values of variables [X] and respectively [Y], so
        that we can refer to them in the postcondition (5).
      - We work backwards mechanically starting from (5) all the way
        to (2). At each step, we obtain the precondition of the
        assignment from its postcondition by substituting the assigned
        variable with the right-hand-side of the assignment. For
        instance, we obtain (4) by substituting [X] with [X - Y]
        in (5), and (3) by substituting [Y] with [X - Y] in (4).
      - Finally, we verify that (1) logically implies (2) -- i.e.,
        that the step from (1) to (2) is a valid use of the law of
        consequence. For this we substitute [X] by [m] and [Y] by [n]
        and calculate as follows:
            (m + n) - ((m + n) - n) = n /\ (m + n) - n = m
            (m + n) - m = n /\ m = m
            n = n /\ m = m

    (Note that, since we are working with natural numbers, not
    fixed-size machine integers, we don't need to worry about the
    possibility of arithmetic overflow anywhere in this argument.)
*)

(* ####################################################### *)
(** ** Example: Simple Conditionals *)

(** Here is a simple decorated program using conditionals:
 (1)     {{True}}
       IFB X <= Y THEN
 (2)       {{True /\ X <= Y}} ->>
 (3)       {{(Y - X) + X = Y \/ (Y - X) + Y = X}}
         Z ::= Y - X
 (4)       {{Z + X = Y \/ Z + Y = X}}
       ELSE
 (5)       {{True /\ ~(X <= Y) }} ->>
 (6)       {{(X - Y) + X = Y \/ (X - Y) + Y = X}}
         Z ::= X - Y
 (7)       {{Z + X = Y \/ Z + Y = X}}
       FI
 (8)     {{Z + X = Y \/ Z + Y = X}}

These decorations were constructed as follows:
  - We start with the outer precondition (1) and postcondition (8).
  - We follow the format dictated by the [hoare_if] rule and copy the
    postcondition (8) to (4) and (7). We conjoin the precondition (1)
    with the guard of the conditional to obtain (2). We conjoin (1)
    with the negated guard of the conditional to obtain (5).
  - In order to use the assignment rule and obtain (3), we substitute
    [Z] by [Y - X] in (4). To obtain (6) we substitute [Z] by [X - Y]
    in (7).
  - Finally, we verify that (2) implies (3) and (5) implies (6). Both
    of these implications crucially depend on the ordering of [X] and
    [Y] obtained from the guard. For instance, knowing that [X <= Y]
    ensures that subtracting [X] from [Y] and then adding back [X]
    produces [Y], as required by the first disjunct of (3). Similarly,
    knowing that [~(X <= Y)] ensures that subtracting [Y] from [X] and
    then adding back [Y] produces [X], as needed by the second
    disjunct of (6). Note that [n - m + m = n] does _not_ hold for
    arbitrary natural numbers [n] and [m] (for example, [3 - 5 + 5 =
    5]). *)

(** **** Exercise: 2 stars (if_minus_plus_reloaded)  *)
(** Fill in valid decorations for the following program:
   {{ True }}
  IFB X <= Y THEN
      {{                         }} ->>
      {{                         }}
    Z ::= Y - X
      {{                         }}
  ELSE
      {{                         }} ->>
      {{                         }}
    Y ::= X + Z
      {{                         }}
  FI
    {{ Y = X + Z }}
*)

(** [] *)

(* ####################################################### *)
(** ** Example: Reduce to Zero (Trivial Loop) *)

(** Here is a [WHILE] loop that is so simple it needs no
    invariant (i.e., the invariant [True] will do the job).
 (1)      {{ True }}
        WHILE X <> 0 DO
 (2)        {{ True /\ X <> 0 }} ->>
 (3)        {{ True }}
          X ::= X - 1
 (4)        {{ True }}
        END
 (5)      {{ True /\ X = 0 }} ->>
 (6)      {{ X = 0 }}
The decorations can be constructed as follows:
  - Start with the outer precondition (1) and postcondition (6).
  - Following the format dictated by the [hoare_while] rule, we copy
    (1) to (4). We conjoin (1) with the guard to obtain (2) and with
    the negation of the guard to obtain (5). Note that, because the
    outer postcondition (6) does not syntactically match (5), we need a
    trivial use of the consequence rule from (5) to (6).
  - Assertion (3) is the same as (4), because [X] does not appear in
    [4], so the substitution in the assignment rule is trivial.
  - Finally, the implication between (2) and (3) is also trivial.
*)

(** From this informal proof, it is easy to read off a formal proof
    using the Coq versions of the Hoare rules.  Note that we do _not_
    unfold the definition of [hoare_triple] anywhere in this proof --
    the idea is to use the Hoare rules as a "self-contained" logic for
    reasoning about programs. *)

Definition reduce_to_zero' : com :=
  WHILE BNot (BEq (AId X) (ANum 0)) DO
    X ::= AMinus (AId X) (ANum 1)
  END.

Theorem reduce_to_zero_correct' :
  {{fun st => True}}
  reduce_to_zero'
  {{fun st => st X = 0}}.
Proof.
  unfold reduce_to_zero'.
  (* First we need to transform the postcondition so
     that hoare_while will apply. *)
  eapply hoare_consequence_post.
  apply hoare_while.
  Case "Loop body preserves invariant".
    (* Need to massage precondition before [hoare_asgn] applies *)
    eapply hoare_consequence_pre. apply hoare_asgn.
    (* Proving trivial implication (2) ->> (3) *)
    intros st [HT Hbp]. unfold assn_sub. apply I.
  Case "Invariant and negated guard imply postcondition".
    intros st [Inv GuardFalse].
    unfold bassn in GuardFalse. simpl in GuardFalse.
    (* SearchAbout helps to find the right lemmas *)
    SearchAbout [not true].
    rewrite not_true_iff_false in GuardFalse.
    SearchAbout [negb false].
    rewrite negb_false_iff in GuardFalse.
    SearchAbout [beq_nat true].
    apply beq_nat_true in GuardFalse.
    apply GuardFalse. Qed.

(* ####################################################### *)
(** ** Example: Division *)

(** The following Imp program calculates the integer division and
    remainder of two numbers [m] and [n] that are arbitrary constants
    in the program.
  X ::= m;;
  Y ::= 0;;
  WHILE n <= X DO
    X ::= X - n;;
    Y ::= Y + 1
  END;
    In other words, if we replace [m] and [n] by concrete numbers and
    execute the program, it will terminate with the variable [X] set
    to the remainder when [m] is divided by [n] and [Y] set to the
    quotient. *)

(** In order to give a specification to this program we need to
    remember that dividing [m] by [n] produces a reminder [X] and a
    quotient [Y] so that [n * Y + X = m /\ X < n].

    It turns out that we get lucky with this program and don't have to
    think very hard about the loop invariant: the invariant is the
    just first conjunct [n * Y + X = m], so we use that to decorate
    the program.

 (1)    {{ True }} ->>
 (2)    {{ n * 0 + m = m }}
      X ::= m;;
 (3)    {{ n * 0 + X = m }}
      Y ::= 0;;
 (4)    {{ n * Y + X = m }}
      WHILE n <= X DO
 (5)      {{ n * Y + X = m /\ n <= X }} ->>
 (6)      {{ n * (Y + 1) + (X - n) = m }}
        X ::= X - n;;
 (7)      {{ n * (Y + 1) + X = m }}
        Y ::= Y + 1
 (8)      {{ n * Y + X = m }}
      END
 (9)    {{ n * Y + X = m /\ X < n }}

    Assertions (4), (5), (8), and (9) are derived mechanically from
    the invariant and the loop's guard. Assertions (8), (7), and (6)
    are derived using the assignment rule going backwards from (8) to
    (6). Assertions (4), (3), and (2) are again backwards applications
    of the assignment rule.

    Now that we've decorated the program it only remains to check that
    the two uses of the consequence rule are correct -- i.e., that (1)
    implies (2) and that (5) implies (6).  This is indeed the case, so
    we have a valid decorated program.
*)

(* ####################################################### *)
(** * Finding Loop Invariants *)

(** Once the outermost precondition and postcondition are chosen, the
    only creative part in verifying programs with Hoare Logic is
    finding the right loop invariants.  The reason this is difficult
    is the same as the reason that doing inductive mathematical proofs
    requires creativity: strengthening the loop invariant (or the
    induction hypothesis) means that you have a stronger assumption to
    work with when trying to establish the postcondition of the loop
    body (complete the induction step of the proof), but it also means
    that the loop body postcondition itself is harder to prove!

    This section is dedicated to teaching you how to approach the
    challenge of finding loop invariants using a series of examples
    and exercises. *)

(** ** Example: Slow Subtraction *)

(** The following program subtracts the value of [X] from the value of
    [Y] by repeatedly decrementing both [X] and [Y]. We want to verify its
    correctness with respect to the following specification:
             {{ X = m /\ Y = n }}
           WHILE X <> 0 DO
             Y ::= Y - 1;;
             X ::= X - 1
           END
             {{ Y = n - m }}

    To verify this program we need to find an invariant [I] for the
    loop. As a first step we can leave [I] as an unknown and build a
    _skeleton_ for the proof by applying backward the rules for local
    consistency. This process leads to the following skeleton:
    (1)      {{ X = m /\ Y = n }}  ->>     (a)
    (2)      {{ I }}
           WHILE X <> 0 DO
    (3)        {{ I /\ X <> 0 }}  ->>      (c)
    (4)        {{ I[X |-> X-1][Y |-> Y-1] }}
             Y ::= Y - 1;;
    (5)        {{ I[X |-> X-1] }}
             X ::= X - 1
    (6)        {{ I }}
           END
    (7)      {{ I /\ ~(X <> 0) }}  ->>         (b)
    (8)      {{ Y = n - m }}

    By examining this skeleton, we can see that any valid [I] will
    have to respect three conditions:
    - (a) it must be weak enough to be implied by the loop's
      precondition, i.e. (1) must imply (2);
    - (b) it must be strong enough to imply the loop's postcondition,
      i.e. (7) must imply (8);
    - (c) it must be preserved by one iteration of the loop, i.e. (3)
      must imply (4). *)

(** These conditions are actually independent of the particular
    program and specification we are considering. Indeed, every loop
    invariant has to satisfy them. One way to find an invariant that
    simultaneously satisfies these three conditions is by using an
    iterative process: start with a "candidate" invariant (e.g. a
    guess or a heuristic choice) and check the three conditions above;
    if any of the checks fails, try to use the information that we get
    from the failure to produce another (hopefully better) candidate
    invariant, and repeat the process.

    For instance, in the reduce-to-zero example above, we saw that,
    for a very simple loop, choosing [True] as an invariant did the
    job. So let's try it again here!  I.e., let's instantiate [I] with
    [True] in the skeleton above see what we get...
    (1)      {{ X = m /\ Y = n }} ->>       (a - OK)
    (2)      {{ True }}
           WHILE X <> 0 DO
    (3)        {{ True /\ X <> 0 }}  ->>    (c - OK)
    (4)        {{ True }}
             Y ::= Y - 1;;
    (5)        {{ True }}
             X ::= X - 1
    (6)        {{ True }}
           END
    (7)      {{ True /\ X = 0 }}  ->>       (b - WRONG!)
    (8)      {{ Y = n - m }}

    While conditions (a) and (c) are trivially satisfied,
    condition (b) is wrong, i.e. it is not the case that (7) [True /\
    X = 0] implies (8) [Y = n - m].  In fact, the two assertions are
    completely unrelated and it is easy to find a counterexample (say,
    [Y = X = m = 0] and [n = 1]).

    If we want (b) to hold, we need to strengthen the invariant so
    that it implies the postcondition (8).  One very simple way to do
    this is to let the invariant _be_ the postcondition.  So let's
    return to our skeleton, instantiate [I] with [Y = n - m], and
    check conditions (a) to (c) again.
    (1)      {{ X = m /\ Y = n }}  ->>          (a - WRONG!)
    (2)      {{ Y = n - m }}
           WHILE X <> 0 DO
    (3)        {{ Y = n - m /\ X <> 0 }}  ->>   (c - WRONG!)
    (4)        {{ Y - 1 = n - m }}
             Y ::= Y - 1;;
    (5)        {{ Y = n - m }}
             X ::= X - 1
    (6)        {{ Y = n - m }}
           END
    (7)      {{ Y = n - m /\ X = 0 }}  ->>      (b - OK)
    (8)      {{ Y = n - m }}

    This time, condition (b) holds trivially, but (a) and (c) are
    broken. Condition (a) requires that (1) [X = m /\ Y = n]
    implies (2) [Y = n - m].  If we substitute [Y] by [n] we have to
    show that [n = n - m] for arbitrary [m] and [n], which does not
    hold (for instance, when [m = n = 1]).  Condition (c) requires that
    [n - m - 1 = n - m], which fails, for instance, for [n = 1] and [m =
    0]. So, although [Y = n - m] holds at the end of the loop, it does
    not hold from the start, and it doesn't hold on each iteration;
    it is not a correct invariant.

    This failure is not very surprising: the variable [Y] changes
    during the loop, while [m] and [n] are constant, so the assertion
    we chose didn't have much chance of being an invariant!

    To do better, we need to generalize (8) to some statement that is
    equivalent to (8) when [X] is [0], since this will be the case
    when the loop terminates, and that "fills the gap" in some
    appropriate way when [X] is nonzero.  Looking at how the loop
    works, we can observe that [X] and [Y] are decremented together
    until [X] reaches [0].  So, if [X = 2] and [Y = 5] initially,
    after one iteration of the loop we obtain [X = 1] and [Y = 4];
    after two iterations [X = 0] and [Y = 3]; and then the loop stops.
    Notice that the difference between [Y] and [X] stays constant
    between iterations; initially, [Y = n] and [X = m], so this
    difference is always [n - m].  So let's try instantiating [I] in
    the skeleton above with [Y - X = n - m].
    (1)      {{ X = m /\ Y = n }}  ->>               (a - OK)
    (2)      {{ Y - X = n - m }}
           WHILE X <> 0 DO
    (3)        {{ Y - X = n - m /\ X <> 0 }}  ->>    (c - OK)
    (4)        {{ (Y - 1) - (X - 1) = n - m }}
             Y ::= Y - 1;;
    (5)        {{ Y - (X - 1) = n - m }}
             X ::= X - 1
    (6)        {{ Y - X = n - m }}
           END
    (7)      {{ Y - X = n - m /\ X = 0 }}  ->>       (b - OK)
    (8)      {{ Y = n - m }}

    Success!  Conditions (a), (b) and (c) all hold now.  (To
    verify (c), we need to check that, under the assumption that [X <>
    0], we have [Y - X = (Y - 1) - (X - 1)]; this holds for all
    natural numbers [X] and [Y].) *)

(* ####################################################### *)
(** ** Exercise: Slow Assignment *)

(** **** Exercise: 2 stars (slow_assignment)  *)
(** A roundabout way of assigning a number currently stored in [X] to
    the variable [Y] is to start [Y] at [0], then decrement [X] until
    it hits [0], incrementing [Y] at each step. Here is a program that
    implements this idea:
      {{ X = m }}
    Y ::= 0;;
    WHILE X <> 0 DO
      X ::= X - 1;;
      Y ::= Y + 1
    END
      {{ Y = m }}
    Write an informal decorated program showing that this is correct. *)

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

(* ####################################################### *)
(** ** Exercise: Slow Addition *)

(** **** Exercise: 3 stars, optional (add_slowly_decoration)  *)
(** The following program adds the variable X into the variable Z
    by repeatedly decrementing X and incrementing Z.
  WHILE X <> 0 DO
     Z ::= Z + 1;;
     X ::= X - 1
  END

    Following the pattern of the [subtract_slowly] example above, pick
    a precondition and postcondition that give an appropriate
    specification of [add_slowly]; then (informally) decorate the
    program accordingly. *)

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

(* ####################################################### *)
(** ** Example: Parity *)

(** Here is a cute little program for computing the parity of the
    value initially stored in [X] (due to Daniel Cristofani).
    {{ X = m }}
  WHILE 2 <= X DO
    X ::= X - 2
  END
    {{ X = parity m }}
    The mathematical [parity] function used in the specification is
    defined in Coq as follows: *)

Fixpoint parity x :=
  match x with
  | 0 => 0
  | 1 => 1
  | S (S x') => parity x'
  end.

(** The postcondition does not hold at the beginning of the loop,
    since [m = parity m] does not hold for an arbitrary [m], so we
    cannot use that as an invariant.  To find an invariant that works,
    let's think a bit about what this loop does.  On each iteration it
    decrements [X] by [2], which preserves the parity of [X].  So the
    parity of [X] does not change, i.e. it is invariant.  The initial
    value of [X] is [m], so the parity of [X] is always equal to the
    parity of [m]. Using [parity X = parity m] as an invariant we
    obtain the following decorated program:
    {{ X = m }} ->>                              (a - OK)
    {{ parity X = parity m }}
  WHILE 2 <= X DO
      {{ parity X = parity m /\ 2 <= X }}  ->>    (c - OK)
      {{ parity (X-2) = parity m }}
    X ::= X - 2
      {{ parity X = parity m }}
  END
    {{ parity X = parity m /\ X < 2 }}  ->>       (b - OK)
    {{ X = parity m }}

    With this invariant, conditions (a), (b), and (c) are all
    satisfied. For verifying (b), we observe that, when [X < 2], we
    have [parity X = X] (we can easily see this in the definition of
    [parity]).  For verifying (c), we observe that, when [2 <= X], we
    have [parity X = parity (X-2)]. *)

(** **** Exercise: 3 stars, optional (parity_formal)  *)
(** Translate this proof to Coq. Refer to the reduce-to-zero example
    for ideas. You may find the following two lemmas useful: *)

Lemma parity_ge_2 : forall x,
  2 <= x ->
  parity (x - 2) = parity x.
Proof.
  induction x; intro. reflexivity.
  destruct x. inversion H. inversion H1.
  simpl. rewrite <- minus_n_O. reflexivity.
Qed.

Lemma parity_lt_2 : forall x,
  ~ 2 <= x ->
  parity (x) = x.
Proof.
  intros. induction x. reflexivity. destruct x. reflexivity.
    apply ex_falso_quodlibet. apply H. omega.
Qed.

Theorem parity_correct : forall m,
    {{ fun st => st X = m }}
  WHILE BLe (ANum 2) (AId X) DO
    X ::= AMinus (AId X) (ANum 2)
  END
    {{ fun st => st X = parity m }}.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ####################################################### *)
(** ** Example: Finding Square Roots *)

(** The following program computes the square root of [X]
    by naive iteration:
      {{ X=m }}
    Z ::= 0;;
    WHILE (Z+1)*(Z+1) <= X DO
      Z ::= Z+1
    END
      {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
*)

(** As above, we can try to use the postcondition as a candidate
    invariant, obtaining the following decorated program:
 (1)  {{ X=m }}  ->>           (a - second conjunct of (2) WRONG!)
 (2)  {{ 0*0 <= m /\ m<1*1 }}
    Z ::= 0;;
 (3)  {{ Z*Z <= m /\ m<(Z+1)*(Z+1) }}
    WHILE (Z+1)*(Z+1) <= X DO
 (4)    {{ Z*Z<=m /\ (Z+1)*(Z+1)<=X }}  ->>           (c - WRONG!)
 (5)    {{ (Z+1)*(Z+1)<=m /\ m<(Z+2)*(Z+2) }}
      Z ::= Z+1
 (6)    {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}
    END
 (7)  {{ Z*Z<=m /\ m<(Z+1)*(Z+1) /\ X<(Z+1)*(Z+1) }}  ->> (b - OK)
 (8)  {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}

    This didn't work very well: both conditions (a) and (c) failed.
    Looking at condition (c), we see that the second conjunct of (4)
    is almost the same as the first conjunct of (5), except that (4)
    mentions [X] while (5) mentions [m]. But note that [X] is never
    assigned in this program, so we should have [X=m], but we didn't
    propagate this information from (1) into the loop invariant.

    Also, looking at the second conjunct of (8), it seems quite
    hopeless as an invariant -- and we don't even need it, since we
    can obtain it from the negation of the guard (third conjunct
    in (7)), again under the assumption that [X=m].

    So we now try [X=m /\ Z*Z <= m] as the loop invariant:
      {{ X=m }}  ->>                                      (a - OK)
      {{ X=m /\ 0*0 <= m }}
    Z ::= 0;
      {{ X=m /\ Z*Z <= m }}
    WHILE (Z+1)*(Z+1) <= X DO
        {{ X=m /\ Z*Z<=m /\ (Z+1)*(Z+1)<=X }}  ->>        (c - OK)
        {{ X=m /\ (Z+1)*(Z+1)<=m }}
      Z ::= Z+1
        {{ X=m /\ Z*Z<=m }}
    END
      {{ X=m /\ Z*Z<=m /\ X<(Z+1)*(Z+1) }}  ->>           (b - OK)
      {{ Z*Z<=m /\ m<(Z+1)*(Z+1) }}

    This works, since conditions (a), (b), and (c) are now all
    trivially satisfied.

    Very often, if a variable is used in a loop in a read-only
    fashion (i.e., it is referred to by the program or by the
    specification and it is not changed by the loop) it is necessary
    to add the fact that it doesn't change to the loop invariant. *)

(* ####################################################### *)
(** ** Example: Squaring *)

(** Here is a program that squares [X] by repeated addition:

    {{ X = m }}
  Y ::= 0;;
  Z ::= 0;;
  WHILE  Y  <>  X  DO
    Z ::= Z + X;;
    Y ::= Y + 1
  END
    {{ Z = m*m }}
*)

(** The first thing to note is that the loop reads [X] but doesn't
    change its value. As we saw in the previous example, in such cases
    it is a good idea to add [X = m] to the invariant. The other thing
    we often use in the invariant is the postcondition, so let's add
    that too, leading to the invariant candidate [Z = m * m /\ X = m].
      {{ X = m }} ->>                            (a - WRONG)
      {{ 0 = m*m /\ X = m }}
    Y ::= 0;;
      {{ 0 = m*m /\ X = m }}
    Z ::= 0;;
      {{ Z = m*m /\ X = m }}
    WHILE Y <> X DO
        {{ Z = Y*m /\ X = m /\ Y <> X }} ->>     (c - WRONG)
        {{ Z+X = m*m /\ X = m }}
      Z ::= Z + X;;
        {{ Z = m*m /\ X = m }}
      Y ::= Y + 1
        {{ Z = m*m /\ X = m }}
    END
      {{ Z = m*m /\ X = m /\ Y = X }} ->>         (b - OK)
      {{ Z = m*m }}

    Conditions (a) and (c) fail because of the [Z = m*m] part.  While
    [Z] starts at [0] and works itself up to [m*m], we can't expect
    [Z] to be [m*m] from the start.  If we look at how [Z] progesses
    in the loop, after the 1st iteration [Z = m], after the 2nd
    iteration [Z = 2*m], and at the end [Z = m*m].  Since the variable
    [Y] tracks how many times we go through the loop, we derive the
    new invariant candidate [Z = Y*m /\ X = m].
      {{ X = m }} ->>                               (a - OK)
      {{ 0 = 0*m /\ X = m }}
    Y ::= 0;;
      {{ 0 = Y*m /\ X = m }}
    Z ::= 0;;
      {{ Z = Y*m /\ X = m }}
    WHILE Y <> X DO
        {{ Z = Y*m /\ X = m /\ Y <> X }} ->>        (c - OK)
        {{ Z+X = (Y+1)*m /\ X = m }}
      Z ::= Z + X;
        {{ Z = (Y+1)*m /\ X = m }}
      Y ::= Y + 1
        {{ Z = Y*m /\ X = m }}
    END
      {{ Z = Y*m /\ X = m /\ Y = X }} ->>           (b - OK)
      {{ Z = m*m }}

    This new invariant makes the proof go through: all three
    conditions are easy to check.

    It is worth comparing the postcondition [Z = m*m] and the [Z =
    Y*m] conjunct of the invariant. It is often the case that one has
    to replace auxiliary variabes (parameters) with variables -- or
    with expressions involving both variables and parameters (like
    [m - Y]) -- when going from postconditions to invariants. *)

(* ####################################################### *)
(** ** Exercise: Factorial *)

(** **** Exercise: 3 stars (factorial)  *)
(** Recall that [n!] denotes the factorial of [n] (i.e. [n! =
    1*2*...*n]).  Here is an Imp program that calculates the factorial
    of the number initially stored in the variable [X] and puts it in
    the variable [Y]:
    {{ X = m }}
  Y ::= 1 ;;
  WHILE X <> 0
  DO
     Y ::= Y * X ;;
     X ::= X - 1
  END
    {{ Y = m! }}

    Fill in the blanks in following decorated program:
    {{ X = m }} ->>
    {{                                      }}
  Y ::= 1;;
    {{                                      }}
  WHILE X <> 0
  DO   {{                                      }} ->>
       {{                                      }}
     Y ::= Y * X;;
       {{                                      }}
     X ::= X - 1
       {{                                      }}
  END
    {{                                      }} ->>
    {{ Y = m! }}
*)

(** [] *)

(* ####################################################### *)
(** ** Exercise: Min *)

(** **** Exercise: 3 stars (Min_Hoare)  *)
(** Fill in valid decorations for the following program.
  For the => steps in your annotations, you may rely (silently) on the
  following facts about min

  Lemma lemma1 : forall x y,
  (x=0 \/ y=0) -> min x y = 0.
  Lemma lemma2 : forall x y,
  min (x-1) (y-1) = (min x y) - 1.

  plus, as usual, standard high-school algebra.

  {{ True }} ->>
  {{                    }}
  X ::= a;;
  {{                       }}
  Y ::= b;;
  {{                       }}
  Z ::= 0;;
  {{                       }}
  WHILE (X <> 0 /\ Y <> 0) DO
  {{                                     }} ->>
  {{                                }}
  X := X - 1;;
  {{                            }}
  Y := Y - 1;;
  {{                        }}
  Z := Z + 1
  {{                       }}
  END
  {{                            }} ->>
  {{ Z = min a b }}
*)

(** [] *)

(** **** Exercise: 3 stars (two_loops)  *)
(** Here is a very inefficient way of adding 3 numbers:
  X ::= 0;;
  Y ::= 0;;
  Z ::= c;;
  WHILE X <> a DO
    X ::= X + 1;;
    Z ::= Z + 1
  END;;
  WHILE Y <> b DO
    Y ::= Y + 1;;
    Z ::= Z + 1
  END

    Show that it does what it should by filling in the blanks in the
    following decorated program.

    {{ True }} ->>
    {{                                        }}
  X ::= 0;;
    {{                                        }}
  Y ::= 0;;
    {{                                        }}
  Z ::= c;;
    {{                                        }}
  WHILE X <> a DO
      {{                                        }} ->>
      {{                                        }}
    X ::= X + 1;;
      {{                                        }}
    Z ::= Z + 1
      {{                                        }}
  END;;
    {{                                        }} ->>
    {{                                        }}
  WHILE Y <> b DO
      {{                                        }} ->>
      {{                                        }}
    Y ::= Y + 1;;
      {{                                        }}
    Z ::= Z + 1
      {{                                        }}
  END
    {{                                        }} ->>
    {{ Z = a + b + c }}
*)

(** [] *)

(* ####################################################### *)
(** ** Exercise: Power Series *)

(** **** Exercise: 4 stars, optional (dpow2_down)  *)
(** Here is a program that computes the series:
    [1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]
  X ::= 0;;
  Y ::= 1;;
  Z ::= 1;;
  WHILE X <> m DO
    Z ::= 2 * Z;;
    Y ::= Y + Z;;
    X ::= X + 1
  END
    Write a decorated program for this. *)

(* FILL IN HERE *)

(* ####################################################### *)
(** * Weakest Preconditions (Advanced) *)

(** Some Hoare triples are more interesting than others.
    For example,
      {{ False }}  X ::= Y + 1  {{ X <= 5 }}
    is _not_ very interesting: although it is perfectly valid, it
    tells us nothing useful.  Since the precondition isn't satisfied
    by any state, it doesn't describe any situations where we can use
    the command [X ::= Y + 1] to achieve the postcondition [X <= 5].

    By contrast,
      {{ Y <= 4 /\ Z = 0 }}  X ::= Y + 1 {{ X <= 5 }}
    is useful: it tells us that, if we can somehow create a situation
    in which we know that [Y <= 4 /\ Z = 0], then running this command
    will produce a state satisfying the postcondition.  However, this
    triple is still not as useful as it could be, because the [Z = 0]
    clause in the precondition actually has nothing to do with the
    postcondition [X <= 5].  The _most_ useful triple (for a given
    command and postcondition) is this one:
      {{ Y <= 4 }}  X ::= Y + 1  {{ X <= 5 }}
    In other words, [Y <= 4] is the _weakest_ valid precondition of
    the command [X ::= Y + 1] for the postcondition [X <= 5]. *)

(** In general, we say that "[P] is the weakest precondition of
    command [c] for postcondition [Q]" if [{{P}} c {{Q}}] and if,
    whenever [P'] is an assertion such that [{{P'}} c {{Q}}], we have
    [P' st] implies [P st] for all states [st].  *)

Definition is_wp P c Q :=
  {{P}} c {{Q}} /\
  forall P', {{P'}} c {{Q}} -> (P' ->> P).

(** That is, [P] is the weakest precondition of [c] for [Q]
    if (a) [P] _is_ a precondition for [Q] and [c], and (b) [P] is the
    _weakest_ (easiest to satisfy) assertion that guarantees [Q] after
    executing [c]. *)

(** **** Exercise: 1 star, optional (wp)  *)
(** What are the weakest preconditions of the following commands
   for the following postconditions?
  1) {{ ? }}  SKIP  {{ X = 5 }}

  2) {{ ? }}  X ::= Y + Z {{ X = 5 }}

  3) {{ ? }}  X ::= Y  {{ X = Y }}

  4) {{ ? }}
     IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI
     {{ Y = 5 }}

  5) {{ ? }}
     X ::= 5
     {{ X = 0 }}

  6) {{ ? }}
     WHILE True DO X ::= 0 END
     {{ X = 0 }}
*)
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (is_wp_formal)  *)
(** Prove formally using the definition of [hoare_triple] that [Y <= 4]
   is indeed the weakest precondition of [X ::= Y + 1] with respect to
   postcondition [X <= 5]. *)

Theorem is_wp_example :
  is_wp (fun st => st Y <= 4)
    (X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced (hoare_asgn_weakest)  *)
(** Show that the precondition in the rule [hoare_asgn] is in fact the
    weakest precondition. *)

Theorem hoare_asgn_weakest : forall Q X a,
  is_wp (Q [X |-> a]) (X ::= a) Q.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, advanced, optional (hoare_havoc_weakest)  *)
(** Show that your [havoc_pre] rule from the [himp_hoare] exercise
    in the [Hoare] chapter returns the weakest precondition. *)
Module Himp2.
Import Himp.

Lemma hoare_havoc_weakest : forall (P Q : Assertion) (X : id),
  {{ P }} HAVOC X {{ Q }} ->
  P ->> havoc_pre X Q.
Proof.
(* FILL IN HERE *) Admitted.
End Himp2.
(** [] *)

(* ####################################################### *)
(** * Formal Decorated Programs (Advanced) *)

(** The informal conventions for decorated programs amount to a way of
    displaying Hoare triples in which commands are annotated with
    enough embedded assertions that checking the validity of the
    triple is reduced to simple logical and algebraic calculations
    showing that some assertions imply others.  In this section, we
    show that this informal presentation style can actually be made
    completely formal and indeed that checking the validity of
    decorated programs can mostly be automated.  *)

(** ** Syntax *)

(** The first thing we need to do is to formalize a variant of the
    syntax of commands with embedded assertions.  We call the new
    commands _decorated commands_, or [dcom]s. *)

Inductive dcom : Type :=
  | DCSkip :  Assertion -> dcom
  | DCSeq : dcom -> dcom -> dcom
  | DCAsgn : id -> aexp ->  Assertion -> dcom
  | DCIf : bexp ->  Assertion -> dcom ->  Assertion -> dcom
           -> Assertion-> dcom
  | DCWhile : bexp -> Assertion -> dcom -> Assertion -> dcom
  | DCPre : Assertion -> dcom -> dcom
  | DCPost : dcom -> Assertion -> dcom.

Tactic Notation "dcom_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "Skip" | Case_aux c "Seq" | Case_aux c "Asgn"
  | Case_aux c "If" | Case_aux c "While"
  | Case_aux c "Pre" | Case_aux c "Post" ].

Notation "'SKIP' {{ P }}"
      := (DCSkip P)
      (at level 10) : dcom_scope.
Notation "l '::=' a {{ P }}"
      := (DCAsgn l a P)
      (at level 60, a at next level) : dcom_scope.
Notation "'WHILE' b 'DO' {{ Pbody }} d 'END' {{ Ppost }}"
      := (DCWhile b Pbody d Ppost)
      (at level 80, right associativity) : dcom_scope.
Notation "'IFB' b 'THEN' {{ P }} d 'ELSE' {{ P' }} d' 'FI' {{ Q }}"
      := (DCIf b P d P' d' Q)
      (at level 80, right associativity)  : dcom_scope.
Notation "'->>' {{ P }} d"
      := (DCPre P d)
      (at level 90, right associativity)  : dcom_scope.
Notation "{{ P }} d"
      := (DCPre P d)
      (at level 90)  : dcom_scope.
Notation "d '->>' {{ P }}"
      := (DCPost d P)
      (at level 80, right associativity)  : dcom_scope.
Notation " d ;; d' "
      := (DCSeq d d')
      (at level 80, right associativity)  : dcom_scope.

Delimit Scope dcom_scope with dcom.

(** To avoid clashing with the existing [Notation] definitions
    for ordinary [com]mands, we introduce these notations in a special
    scope called [dcom_scope], and we wrap examples with the
    declaration [% dcom] to signal that we want the notations to be
    interpreted in this scope.

    Careful readers will note that we've defined two notations for the
    [DCPre] constructor, one with and one without a [->>].  The
    "without" version is intended to be used to supply the initial
    precondition at the very top of the program. *)

Example dec_while : dcom := (
  {{ fun st => True }}
  WHILE (BNot (BEq (AId X) (ANum 0)))
  DO
    {{ fun st => True /\ st X <> 0}}
    X ::= (AMinus (AId X) (ANum 1))
    {{ fun _ => True }}
  END
  {{ fun st => True /\ st X = 0}} ->>
  {{ fun st => st X = 0 }}
) % dcom.

(** It is easy to go from a [dcom] to a [com] by erasing all
    annotations. *)

Fixpoint extract (d:dcom) : com :=
  match d with
  | DCSkip _           => SKIP
  | DCSeq d1 d2        => (extract d1 ;; extract d2)
  | DCAsgn X a _       => X ::= a
  | DCIf b _ d1 _ d2 _ => IFB b THEN extract d1 ELSE extract d2 FI
  | DCWhile b _ d _    => WHILE b DO extract d END
  | DCPre _ d          => extract d
  | DCPost d _         => extract d
  end.

(** The choice of exactly where to put assertions in the definition of
    [dcom] is a bit subtle.  The simplest thing to do would be to
    annotate every [dcom] with a precondition and postcondition.  But
    this would result in very verbose programs with a lot of repeated
    annotations: for example, a program like [SKIP;SKIP] would have to
    be annotated as
        {{P}} ({{P}} SKIP {{P}}) ;; ({{P}} SKIP {{P}}) {{P}},
    with pre- and post-conditions on each [SKIP], plus identical pre-
    and post-conditions on the semicolon!

    Instead, the rule we've followed is this:

       - The _post_-condition expected by each [dcom] [d] is embedded in [d]

       - The _pre_-condition is supplied by the context. *)

(** In other words, the invariant of the representation is that a
    [dcom] [d] together with a precondition [P] determines a Hoare
    triple [{{P}} (extract d) {{post d}}], where [post] is defined as
    follows: *)

Fixpoint post (d:dcom) : Assertion :=
  match d with
  | DCSkip P                => P
  | DCSeq d1 d2             => post d2
  | DCAsgn X a Q            => Q
  | DCIf  _ _ d1 _ d2 Q     => Q
  | DCWhile b Pbody c Ppost => Ppost
  | DCPre _ d               => post d
  | DCPost c Q              => Q
  end.

(** Similarly, we can extract the "initial precondition" from a
    decorated program. *)

Fixpoint pre (d:dcom) : Assertion :=
  match d with
  | DCSkip P                => fun st => True
  | DCSeq c1 c2             => pre c1
  | DCAsgn X a Q            => fun st => True
  | DCIf  _ _ t _ e _       => fun st => True
  | DCWhile b Pbody c Ppost => fun st => True
  | DCPre P c               => P
  | DCPost c Q              => pre c
  end.

(** This function is not doing anything sophisticated like calculating
    a weakest precondition; it just recursively searches for an
    explicit annotation at the very beginning of the program,
    returning default answers for programs that lack an explicit
    precondition (like a bare assignment or [SKIP]). *)

(** Using [pre] and [post], and assuming that we adopt the convention
    of always supplying an explicit precondition annotation at the
    very beginning of our decorated programs, we can express what it
    means for a decorated program to be correct as follows: *)

Definition dec_correct (d:dcom) :=
  {{pre d}} (extract d) {{post d}}.

(** To check whether this Hoare triple is _valid_, we need a way to
    extract the "proof obligations" from a decorated program.  These
    obligations are often called _verification conditions_, because
    they are the facts that must be verified to see that the
    decorations are logically consistent and thus add up to a complete
    proof of correctness. *)

(** ** Extracting Verification Conditions *)

(** The function [verification_conditions] takes a [dcom] [d] together
    with a precondition [P] and returns a _proposition_ that, if it
    can be proved, implies that the triple [{{P}} (extract d) {{post d}}]
    is valid. *)

(** It does this by walking over [d] and generating a big
    conjunction including all the "local checks" that we listed when
    we described the informal rules for decorated programs.  (Strictly
    speaking, we need to massage the informal rules a little bit to
    add some uses of the rule of consequence, but the correspondence
    should be clear.) *)

Fixpoint verification_conditions (P : Assertion) (d:dcom) : Prop :=
  match d with
  | DCSkip Q          =>
      (P ->> Q)
  | DCSeq d1 d2      =>
      verification_conditions P d1
      /\ verification_conditions (post d1) d2
  | DCAsgn X a Q      =>
      (P ->> Q [X |-> a])
  | DCIf b P1 d1 P2 d2 Q =>
      ((fun st => P st /\ bassn b st) ->> P1)
      /\ ((fun st => P st /\ ~ (bassn b st)) ->> P2)
      /\ (Q <<->> post d1) /\ (Q <<->> post d2)
      /\ verification_conditions P1 d1
      /\ verification_conditions P2 d2
  | DCWhile b Pbody d Ppost      =>
      (* post d is the loop invariant and the initial precondition *)
      (P ->> post d)
      /\ (Pbody <<->> (fun st => post d st /\ bassn b st))
      /\ (Ppost <<->> (fun st => post d st /\ ~(bassn b st)))
      /\ verification_conditions Pbody d
  | DCPre P' d         =>
      (P ->> P') /\ verification_conditions P' d
  | DCPost d Q        =>
      verification_conditions P d /\ (post d ->> Q)
  end.

(** And now, the key theorem, which states that
    [verification_conditions] does its job correctly.  Not
    surprisingly, we need to use each of the Hoare Logic rules at some
    point in the proof. *)
(** We have used _in_ variants of several tactics before to
    apply them to values in the context rather than the goal. An
    extension of this idea is the syntax [tactic in *], which applies
    [tactic] in the goal and every hypothesis in the context.  We most
    commonly use this facility in conjunction with the [simpl] tactic,
    as below. *)

Theorem verification_correct : forall d P,
  verification_conditions P d -> {{P}} (extract d) {{post d}}.
Proof.
  dcom_cases (induction d) Case; intros P H; simpl in *.
  Case "Skip".
    eapply hoare_consequence_pre.
      apply hoare_skip.
      assumption.
  Case "Seq".
    inversion H as [H1 H2]. clear H.
    eapply hoare_seq.
      apply IHd2. apply H2.
      apply IHd1. apply H1.
  Case "Asgn".
    eapply hoare_consequence_pre.
      apply hoare_asgn.
      assumption.
  Case "If".
    inversion H as [HPre1 [HPre2 [[Hd11 Hd12]
                                  [[Hd21 Hd22] [HThen HElse]]]]].
    clear H.
    apply IHd1 in HThen. clear IHd1.
    apply IHd2 in HElse. clear IHd2.
    apply hoare_if.
      eapply hoare_consequence_pre; eauto.
      eapply hoare_consequence_post; eauto.
      eapply hoare_consequence_pre; eauto.
      eapply hoare_consequence_post; eauto.
  Case "While".
    inversion H as [Hpre [[Hbody1 Hbody2] [[Hpost1 Hpost2]  Hd]]];
    subst; clear H.
    eapply hoare_consequence_pre; eauto.
    eapply hoare_consequence_post; eauto.
    apply hoare_while.
    eapply hoare_consequence_pre; eauto.
  Case "Pre".
    inversion H as [HP Hd]; clear H.
    eapply hoare_consequence_pre. apply IHd. apply Hd. assumption.
  Case "Post".
    inversion H as [Hd HQ]; clear H.
    eapply hoare_consequence_post. apply IHd. apply Hd. assumption.
Qed.

(** ** Examples *)

(** The propositions generated by [verification_conditions] are fairly
    big, and they contain many conjuncts that are essentially trivial. *)

Eval simpl in (verification_conditions (fun st => True) dec_while).
(**
==>
(((fun _ : state => True) ->> (fun _ : state => True)) /\
 ((fun _ : state => True) ->> (fun _ : state => True)) /\
 (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) =
 (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
 (fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) =
 (fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) /\
 (fun st : state => True /\ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
 (fun _ : state => True) [X |-> AMinus (AId X) (ANum 1)]) /\
(fun st : state => True /\ ~ bassn (BNot (BEq (AId X) (ANum 0))) st) ->>
(fun st : state => st X = 0)
*)

(** In principle, we could certainly work with them using just the
    tactics we have so far, but we can make things much smoother with
    a bit of automation.  We first define a custom [verify] tactic
    that applies splitting repeatedly to turn all the conjunctions
    into separate subgoals and then uses [omega] and [eauto] (a handy
    general-purpose automation tactic that we'll discuss in detail
    later) to deal with as many of them as possible. *)

Lemma ble_nat_true_iff : forall n m : nat,
  ble_nat n m = true <-> n <= m.
Proof.
  intros n m. split. apply ble_nat_true.
  generalize dependent m. induction n; intros m H. reflexivity.
    simpl. destruct m. inversion H.
    apply le_S_n in H. apply IHn. assumption.
Qed.

Lemma ble_nat_false_iff : forall n m : nat,
  ble_nat n m = false <-> ~(n <= m).
Proof.
  intros n m. split. apply ble_nat_false.
  generalize dependent m. induction n; intros m H.
    apply ex_falso_quodlibet. apply H. apply le_0_n.
    simpl. destruct m. reflexivity.
    apply IHn. intro Hc. apply H. apply le_n_S. assumption.
Qed.

Tactic Notation "verify" :=
  apply verification_correct;
  repeat split;
  simpl; unfold assert_implies;
  unfold bassn in *; unfold beval in *; unfold aeval in *;
  unfold assn_sub; intros;
  repeat rewrite update_eq;
  repeat (rewrite update_neq; [| (intro X; inversion X)]);
  simpl in *;
  repeat match goal with [H : _ /\ _ |- _] => destruct H end;
  repeat rewrite not_true_iff_false in *;
  repeat rewrite not_false_iff_true in *;
  repeat rewrite negb_true_iff in *;
  repeat rewrite negb_false_iff in *;
  repeat rewrite beq_nat_true_iff in *;
  repeat rewrite beq_nat_false_iff in *;
  repeat rewrite ble_nat_true_iff in *;
  repeat rewrite ble_nat_false_iff in *;
  try subst;
  repeat
    match goal with
      [st : state |- _] =>
        match goal with
          [H : st _ = _ |- _] => rewrite -> H in *; clear H
        | [H : _ = st _ |- _] => rewrite <- H in *; clear H
        end
    end;
  try eauto; try omega.

(** What's left after [verify] does its thing is "just the interesting
    parts" of checking that the decorations are correct. For very
    simple examples [verify] immediately solves the goal (provided
    that the annotations are correct). *)

Theorem dec_while_correct :
  dec_correct dec_while.
Proof. verify. Qed.

(** Another example (formalizing a decorated program we've seen
    before): *)

Example subtract_slowly_dec (m:nat) (p:nat) : dcom := (
    {{ fun st => st X = m /\ st Z = p }} ->>
    {{ fun st => st Z - st X = p - m }}
  WHILE BNot (BEq (AId X) (ANum 0))
  DO   {{ fun st => st Z - st X = p - m /\ st X <> 0 }} ->>
       {{ fun st => (st Z - 1) - (st X - 1) = p - m }}
     Z ::= AMinus (AId Z) (ANum 1)
       {{ fun st => st Z - (st X - 1) = p - m }} ;;
     X ::= AMinus (AId X) (ANum 1)
       {{ fun st => st Z - st X = p - m }}
  END
    {{ fun st => st Z - st X = p - m /\ st X = 0 }} ->>
    {{ fun st => st Z = p - m }}
) % dcom.

Theorem subtract_slowly_dec_correct : forall m p,
  dec_correct (subtract_slowly_dec m p).
Proof. intros m p. verify. (* this grinds for a bit! *) Qed.

(** **** Exercise: 3 stars, advanced (slow_assignment_dec)  *)

(** In the [slow_assignment] exercise above, we saw a roundabout way
    of assigning a number currently stored in [X] to the variable [Y]:
    start [Y] at [0], then decrement [X] until it hits [0],
    incrementing [Y] at each step.

    Write a _formal_ version of this decorated program and prove it
    correct. *)

Example slow_assignment_dec (m:nat) : dcom :=
(* FILL IN HERE *) admit.

Theorem slow_assignment_dec_correct : forall m,
  dec_correct (slow_assignment_dec m).
Proof. (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced (factorial_dec)   *)
(** Remember the factorial function we worked with before: *)

Fixpoint real_fact (n:nat) : nat :=
  match n with
  | O => 1
  | S n' => n * (real_fact n')
  end.

(** Following the pattern of [subtract_slowly_dec], write a decorated
    program [factorial_dec] that implements the factorial function and
    prove it correct as [factorial_dec_correct]. *)

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

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


Require Import Basics.
Require Import Types.
Require Import Cone.
Require Import Cocone.
Require Import Diagram.
Require Import Graph.

(** * Constant diagram *)

Section ConstantDiagram.

  Context {G : Graph}.

  Definition diagram_const (C : Type) : Diagram G.
  Proof.
    serapply Build_Diagram.
    1: exact (fun _ => C).
    intros i j k.
    exact idmap.
  Defined.

  Definition diagram_const_functor {A B : Type} (f : A -> B)
    : DiagramMap (diagram_const A) (diagram_const B).
  Proof.
    serapply Build_DiagramMap.
    1: intro i; exact f.
    reflexivity.
  Defined.

  Definition diagram_const_functor_comp {A B C : Type}
    (f : A -> B) (g : B -> C)
    : diagram_const_functor (g o f)
    = diagram_comp (diagram_const_functor g) (diagram_const_functor f).
  Proof.
    reflexivity.
  Defined.

  Definition diagram_const_functor_idmap {A : Type}
    : diagram_const_functor (idmap : A -> A) = diagram_idmap (diagram_const A).
  Proof.
    reflexivity.
  Defined.

  Definition equiv_diagram_const_cocone `{Funext} (D : Diagram G) (X : Type)
    : DiagramMap D (diagram_const X) <~> Cocone D X.
  Proof.
    serapply equiv_adjointify.
    1,2: intros [? w]; econstructor.
    1,2: intros x y z z'; symmetry; revert x y z z'.
    1,2: exact w.
    1,2: intros[].
    1: serapply path_cocone.
    3: serapply path_DiagramMap.
    1,3: reflexivity.
    all: cbn; intros; hott_simpl.
  Defined.

  Definition equiv_diagram_const_cone `{Funext} (X : Type) (D : Diagram G)
    : DiagramMap (diagram_const X) D <~> Cone X D.
  Proof.
    serapply equiv_adjointify.
    1,2: intros [? w]; econstructor.
    1,2: exact w.
    1,2: intros[].
    1: serapply path_cone.
    3: serapply path_DiagramMap.
    1,3: reflexivity.
    all: cbn; intros; hott_simpl.
  Defined.

End ConstantDiagram.


Require Import VST.floyd.proofauto.
Require Import CertiGraph.binheap.binary_heap_model.

(* Versions in Z... *)

Definition Zexchange {A : Type} (L : list A) (i j : Z) : list A :=
  exchange L (Z.to_nat i) (Z.to_nat j).

Lemma Zlength_Zexchange {A : Type} : forall (L : list A) i j,
  Zlength (Zexchange L i j) = Zlength L.
Proof.
  intros. unfold Zexchange. do 2 rewrite Zlength_correct. rewrite exchange_length. trivial.
Qed.

Lemma Zlength_one: forall A (a : A),
  Zlength [a] = 1.
Proof. reflexivity. Qed.

Lemma Znth_nth_error {A} `{Ia : Inhabitant A} : forall (L : list A) (i : Z),
  0 <= i < Zlength L ->
  nth_error L (Z.to_nat i) = Some (Znth i L).
Proof.
  intros. rewrite <- nth_Znth; trivial.
  apply nth_error_nth.
  rewrite <- ZtoNat_Zlength. lia.
Qed.

Lemma nth_error_Znth {A} `{Ia : Inhabitant A}: forall (L1 L2 : list A) i j,
  0 <= i < Zlength L1 ->
  0 <= j < Zlength L2 ->
  nth_error L1 (Z.to_nat i) = nth_error L2 (Z.to_nat j) <->
  Znth i L1 = Znth j L2.
Proof.
  intros.
  assert (Z.to_nat i < length L1 /\ Z.to_nat j < length L2)%nat. {
    generalize (Zlength_length _ L1 (Zlength L1)); intro.
    generalize (Zlength_length _ L2 (Zlength L2)); intro.
    destruct H1. apply Zlength_nonneg.
    destruct H2. apply Zlength_nonneg.
    rewrite (H1 eq_refl). rewrite (H2 eq_refl). lia. }
  repeat rewrite <- nth_Znth; trivial.
  generalize (nth_error_nth A Ia); intros.
  split; intros. do 2 (rewrite H2 in H3; try lia). inversion H3. congruence.
  rewrite H2. rewrite H2. congruence. lia. lia.
Qed.

Lemma Znth_Zexchange : forall {A} `{Ia : Inhabitant A} (L : list A) i j,
  0 <= i < Zlength L ->
  0 <= j < Zlength L ->
  Znth i (Zexchange L i j) = Znth j L.
Proof.
  intros.
  apply nth_error_Znth; auto. rewrite Zlength_Zexchange. trivial.
  generalize (Zlength_length _ L (Zlength L)). intro.
  apply nth_error_exchange; lia.
Qed.

Lemma Znth_Zexchange' : forall {A} `{Ia : Inhabitant A} (L : list A) i j,
  0 <= i < Zlength L ->
  0 <= j < Zlength L ->
  Znth j (Zexchange L i j) = Znth i L.
Proof.
  intros.
  apply nth_error_Znth; auto. rewrite Zlength_Zexchange. trivial.
  generalize (Zlength_length _ L (Zlength L)). intro.
  apply nth_error_exchange'; lia.
Qed.

Lemma Znth_Zexchange'' : forall {A} `{Ia : Inhabitant A} (L : list A) k i j,
  0 <= i < Zlength L ->
  0 <= j < Zlength L ->
  k <> i -> k <> j ->
  Znth k (Zexchange L i j) = Znth k L.
Proof.
  intros.
  assert (k < 0 \/ 0 <= k < Zlength L \/ Zlength L <= k) by lia.
  destruct H3 as [? | [? | ?]].
  repeat rewrite Znth_underflow; trivial.
  2: repeat rewrite Znth_overflow; try rewrite Zlength_Zexchange; trivial; lia.
  apply nth_error_Znth; auto. rewrite Zlength_Zexchange. trivial.
  apply nth_error_exchange''.
  intro. apply H1. apply Z2Nat.inj; lia.
  intro. apply H2. apply Z2Nat.inj; lia.
Qed.

Lemma Zexchange_eq: forall A (L : list A) i,
  Zexchange L i i = L.
Proof. unfold Zexchange. intros. apply exchange_eq. Qed.

Lemma upd_Znth_overwrite:
  forall {A} (l : list A) i a b,
    0 <= i < Zlength l ->
    upd_Znth i (upd_Znth i l a) b = upd_Znth i l b.
Proof.
  intros.
  rewrite upd_Znth_unfold by now rewrite upd_Znth_Zlength.
  rewrite upd_Znth_Zlength; trivial.
  repeat rewrite upd_Znth_unfold by trivial.
  rewrite sublist0_app1.
  2: rewrite Zlength_sublist; lia.
  rewrite sublist_sublist00 by lia.
  f_equal. f_equal.
  rewrite app_assoc.
  rewrite sublist_app2.
  2: { rewrite Zlength_app, Zlength_sublist by lia.
       unfold Zlength. simpl. lia.
  }
  rewrite Zlength_app, Zlength_sublist by lia.
  unfold Zlength at 1; simpl.
  rewrite sublist_same; trivial.
  - lia.
  - unfold Zlength at 2; simpl.
    rewrite Zlength_sublist by lia. lia.
Qed.

Lemma upd_Znth_same_Znth:
  forall {A} `{Ia : Inhabitant A} (l: list A) i,
    0 <= i < Zlength l ->
    upd_Znth i l (Znth i l) = l.
Proof.
  intros. rewrite upd_Znth_unfold by trivial.
  rewrite <- sublist_len_1 by trivial.
  repeat rewrite <- sublist_split.
  apply sublist_same; trivial.
  all: lia.
Qed.

Lemma Zexchange_head_foot: forall A (head : A) body foot,
  Zexchange ((head :: body) ++ [foot]) 0 (Zlength (head :: body)) = ((foot :: body) ++ [head]).
Proof.
  intros.
  unfold Zexchange. simpl.  rewrite Zlength_correct. rewrite Nat2Z.id.
  do 2 rewrite app_comm_cons. apply exchange_head_foot.
Qed.

Lemma Permutation_Zlength: forall A (L1 : list A) L2,
  Permutation L1 L2 ->
  Zlength L1 = Zlength L2.
Proof.
  intros. apply Permutation_length in H. do 2 rewrite Zlength_correct. congruence.
Qed.

Lemma Zexchange_Permutation: forall A (L : list A) i j,
  Permutation L (Zexchange L i j).
Proof.
  intros. unfold Zexchange. symmetry. apply exchange_Permutation.
Qed.

Lemma Permutation_Znth {A : Type} `{iA: Inhabitant A}: forall (l l' : list A) (d : A),
       Permutation l l' <->
       (let n := Zlength l in
        Zlength l' = n /\
        (exists f : nat -> nat,
           FinFun.bFun (Z.to_nat n) f /\
           FinFun.bInjective (Z.to_nat n) f /\
           (forall z : Z, (0 <= z < n) -> Znth z l' = Znth (Z.of_nat (f (Z.to_nat z))) l))).
Proof.
  intros. rewrite Permutation_nth. instantiate (1 := iA). do 2 rewrite Zlength_correct. split; intros; subst n; destruct H as [? [? [? [? ?]]]]; rename x into f.
  * split. congruence.
    exists f. rewrite Nat2Z.id. split; trivial. split; trivial. intros.
    repeat rewrite <- nth_Znth. 3: rewrite Zlength_correct; lia.
    rewrite H2. 2: rep_lia.
    rewrite Nat2Z.id. trivial.
    rewrite Zlength_correct. specialize (H0 (Z.to_nat z)).  rep_lia.
  * split. rep_lia.
    exists f. rewrite Nat2Z.id in *. split; trivial. split; trivial. intros.
    specialize (H2 (Z.of_nat x)).
    do 2 rewrite <- nth_Znth in H2. repeat rewrite Nat2Z.id in *.
    apply H2. lia.
    1,2,3: rewrite Zlength_correct. 2,3: lia.
    specialize (H0 x). rewrite Nat2Z.id. lia.
Qed.

Lemma Zexchange_symm {A}: forall (L : list A) i j,
  0 <= i < Zlength L -> 0 <= j < Zlength L ->
  Zexchange L i j = Zexchange L j i.
Proof.
  intros.
  rewrite Zlength_correct in H, H0.
  apply exchange_symm; lia.
Qed.

Definition Zleft_child i  := Z.of_nat (binary_heap_model.left_child  (Z.to_nat i)).
Lemma Zleft_child_unfold: forall i,
  0 <= i ->
  Zleft_child i = (2 * i) + 1.
Proof.
  unfold Zleft_child, binary_heap_model.left_child. intros.
  do 2 rewrite Nat2Z.inj_add. rewrite Z2Nat.id; lia.
Qed.

Lemma Zleft_child_repr: forall i,
  0 <= i ->
  Int.repr (Zleft_child i) = Int.add (Int.mul (Int.repr 2) (Int.repr i)) Int.one.
Proof.
  intros. rewrite Zleft_child_unfold; trivial.
  unfold Int.one.
  rewrite mul_repr, add_repr. trivial.
Qed.

Definition Zright_child i := Z.of_nat (binary_heap_model.right_child (Z.to_nat i)).
Lemma Zright_child_unfold: forall i,
  Zright_child i = Zleft_child i + 1.
Proof.
  unfold Zright_child, Zleft_child, binary_heap_model.right_child. intros.
  rewrite Nat2Z.inj_add. trivial.
Qed.

Lemma Zright_child_repr: forall i,
  0 <= i ->
  Int.repr (Zright_child i) = Int.mul (Int.repr 2) (Int.add (Int.repr i) Int.one).
Proof.
  intros. rewrite Zright_child_unfold.
  rewrite <- add_repr.
  rewrite Zleft_child_repr; trivial.
  rewrite Int.add_assoc.
  change (Int.add Int.one (Int.repr 1)) with (Int.repr 2).
  rewrite Int.mul_add_distr_r.
  reflexivity.
Qed.

Definition Zparent (i : Z) : Z := Z.of_nat (parent (Z.to_nat i)).
Lemma Zparent_unfold: forall i,
  0 < i ->
  Zparent i = (i - 1) / 2.
Proof.
  unfold Zparent, parent. intros.
  rewrite Nat.div2_div, div_Zdiv; auto.
  rewrite Nat2Z.inj_sub. rewrite Z2Nat.id; lia.
  lia.
Qed.
Lemma Zparent_0:
  Zparent 0 = 0.
Proof. reflexivity. Qed.

Lemma Zparent_repr: forall i,
  0 < i <= Int.max_unsigned ->
  Int.repr (Zparent i) = Int.divu (Int.repr (i - 1)) (Int.repr 2).
Proof.
  intros. unfold Int.divu. repeat rewrite Int.unsigned_repr.
  2,3: rep_lia. rewrite Zparent_unfold. trivial. lia.
Qed.

(*
Lemma heapOrdered_lower_priority_weak_heapOrdered2: forall H,
  heapOrdered H ->
  forall t old,
  nth_error H t = Some old ->
  forall new, new <<= old ->
  weak_heapOrdered2 (update H t new) t.

Lemma heapOrdered_raise_priority_weak_heapOrdered: forall H,
  heapOrdered H ->
  forall t old,
  nth_error H t = Some old ->
  forall new, old <<= new ->
  weak_heapOrdered (update H t new) t.
*)


Require Import Coq.Reals.Rdefinitions.
Require Import TLA.TLA.
Require Import TLA.ProofRules.
Require Import Examples.System.

Open Scope HP_scope.

Section SensorWithError.

  Variable err : R.

  Definition Sense : Formula :=
    "Xmax" <= "Xmin" + err //\\ "Xmin" <= "x" <= "Xmax".

  Definition SenseSafe : Formula :=
    "Xmin" <= "x" <= "Xmax".

  Definition I : Formula := SenseSafe.

  Variable d : R.

  Definition SpecR : SysRec :=
    {| Init := I;
       Prog := Unchanged ("x"::"Xmax"::"Xmin"::nil)%list;
       world := fun _ => Sense;
       unch := (("x":Term)::("Xmax":Term)::("Xmin":Term)::nil)%list;
       maxTime := d |}.

  Definition Spec := SysD SpecR.

  Lemma SysSafe_sense : forall P, P |-- SysSafe SpecR.
  Proof.
    intros.
    apply SysSafe_rule; apply always_tauto.
    enable_ex_st. repeat eexists. solve_linear.
  Qed.

  Theorem sense_safe :
    Spec |-- []SenseSafe.
  Proof.
    eapply Sys_by_induction
      with (IndInv := SenseSafe) (A := ltrue).
    + tlaIntuition.
    + unfold Spec, SpecR. tlaAssume.
    + tlaIntuition.
    + apply SysSafe_sense.
    + tlaAssume.
    + eapply BasicProofRules.always_tauto. charge_tauto.
    + tlaAssume.
    + red. solve_linear.
    + unfold World. rewrite Continuous_st_formula with (F:=Sense).
      * solve_linear.
      * tlaIntuition.
      * tlaIntuition.
      * charge_tauto.
    + solve_linear.
  Qed.

End SensorWithError.

Close Scope HP_scope.