text:
From Test Require Import tactic.

Section FOFProblem.

Variable Universe : Set.
Variable UniverseElement : Universe.

Variable wd_ : Universe -> Universe -> Prop.
Variable col_ : Universe -> Universe -> Universe -> Prop.

Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)).
Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)).
Variable col_triv_3 : (forall A B : Universe, col_ A B B).
Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)).
Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)).

Theorem pipo_6 : (forall A1 A2 B1 B2 C1 C2 D1 D2 IAB IAC IBD E F : Universe, ((wd_ IAB IAC /\ (wd_ IAB IBD /\ (wd_ IAB F /\ (wd_ IBD F /\ (wd_ IAB E /\ (wd_ IAC E /\ (wd_ B1 B2 /\ (wd_ D1 D2 /\ (wd_ A1 A2 /\ (wd_ C1 C2 /\ (col_ A1 A2 IAB /\ (col_ B1 B2 IAB /\ (col_ A1 A2 IAC /\ (col_ C1 C2 IAC /\ (col_ B1 B2 IBD /\ (col_ D1 D2 IBD /\ (col_ IBD IAB F /\ col_ IAC IAB E))))))))))))))))) -> col_ A1 A2 E)).
Proof.
  time tac.
Qed.

End FOFProblem.

author: janicicpredrag

repo: Larus

save_path: github-repos/coq/janicicpredrag-Larus


text:
(********************************************************************)
(*                                                                  *)
(*  The Why3 Verification Platform   /   The Why3 Development Team  *)
(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)
(*                                                                  *)
(*  This software is distributed under the terms of the GNU Lesser  *)
(*  General Public License version 2.1, with the special exception  *)
(*  on linking described in file LICENSE.                           *)
(*                                                                  *)
(********************************************************************)

(* This file is generated by Why3's Coq-realize driver *)
(* Beware! Only edit allowed sections below    *)
Require Import BuiltIn.
Require Reals.R_sqrt.
Require BuiltIn.
Require real.Real.

Import R_sqrt.

(* Why3 goal *)
Lemma sqr_def : forall (x:R), ((Reals.RIneq.Rsqr x) = (x * x)%R).
reflexivity.
Qed.

(* Why3 comment *)
(* sqrt is replaced with (Reals.R_sqrt.sqrt x) by the coq driver *)

(* Why3 goal *)
Lemma Sqrt_positive : forall (x:R), (0%R <= x)%R ->
  (0%R <= (Reals.R_sqrt.sqrt x))%R.
intros x _.
apply sqrt_pos.
Qed.

(* Why3 goal *)
Lemma Sqrt_square : forall (x:R), (0%R <= x)%R ->
  ((Reals.RIneq.Rsqr (Reals.R_sqrt.sqrt x)) = x).
exact sqrt_sqrt.
Qed.

(* Why3 goal *)
Lemma Square_sqrt : forall (x:R), (0%R <= x)%R ->
  ((Reals.R_sqrt.sqrt (x * x)%R) = x).
exact sqrt_square.
Qed.

(* Why3 goal *)
Lemma Sqrt_mul : forall (x:R) (y:R), ((0%R <= x)%R /\ (0%R <= y)%R) ->
  ((Reals.R_sqrt.sqrt (x * y)%R) = ((Reals.R_sqrt.sqrt x) * (Reals.R_sqrt.sqrt y))%R).
intros x y (hx & hy); now apply sqrt_mult.
Qed.

(* Why3 goal *)
Lemma Sqrt_le : forall (x:R) (y:R), ((0%R <= x)%R /\ (x <= y)%R) ->
  ((Reals.R_sqrt.sqrt x) <= (Reals.R_sqrt.sqrt y))%R.
intros x y (h1 & h2); apply sqrt_le_1; auto.
apply Rle_trans with x; auto.
Qed.

author: ssaavedra


text:
(**************************************************************)
(*   Copyright Dominique Larchey-Wendling [*]                 *)
(*                                                            *)
(*                             [*] Affiliation LORIA -- CNRS  *)
(**************************************************************)
(*      This file is distributed under the terms of the       *)
(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)
(**************************************************************)

Require Import List Permutation.

From Undecidability.Shared.Libs.DLW
  Require Import utils.

From Undecidability.ILL Require Import ILL CLL ill_cll.

Set Implicit Arguments.

(* Small inversion lemma *)

Fact app_eq_single_inv X (l m : list X) x :
       l++m = x::nil
    -> l = nil /\ m = x::nil
    \/ l = x::nil /\ m = nil.
Proof.
  intros H.
  destruct l as [ | y l ]; auto.
  right.
  inversion H.
  destruct l; destruct m; auto; discriminate.
Qed.

Tactic Notation "app" "inv" "singleton" "in" hyp(H) :=
  apply app_eq_single_inv in H as [ (-> & ->) | (-> & ->) ].

Tactic Notation "app" "inv" "nil" "in" hyp(H) :=
  apply app_eq_nil in H as (-> & ->).

(* * Classical Linear Logic vs Intuitionnisitc Linear Logic

       derived from the work of H. Schellinx JLC 91 *)

Local Infix "~p" := (@Permutation _) (at level 70).

(* Γ ⊢i A stands for the sequent Γ ⊢ A is cut-free ILL provable *)
(* Γ ⊢c Δ stands for the sequent Γ ⊢ Δ is cut-free CLL provable *)

Notation "Γ '⊢i' A" := (S_ill Γ A) (at level 70, no associativity).
Notation "Γ '⊢c' Δ" := (S_cll Γ Δ) (at level 70, no associativity).

Section ill_cll_is_sound.

  Hint Resolve Permutation_map : core.

  Theorem ill_cll_soundness Γ A : Γ ⊢i A -> ⟦Γ⟧ ⊢c [A]::∅.
  Proof.
    induction 1; simpl in *.
    + apply in_cll_ax.
    + apply (@in_cll_perm ⟦Γ⟧ ([A]::nil)); auto.
    + rewrite map_app.
      now apply in_cll_limp_l with (Δ := ∅) (Δ' := _::_).
    + now apply in_cll_limp_r with (Δ := ∅).
    + now apply in_cll_with_l1.
    + now apply in_cll_with_l2.
    + now apply in_cll_with_r with (Δ := ∅).
    + now apply in_cll_bang_l.
    + rewrite ill_cll_lbang in *.
      now apply in_cll_bang_r with (Δ := ∅).
    + now apply in_cll_weak_l.
    + now apply in_cll_cntr_l.
    + now apply in_cll_times_l.
    + rewrite map_app.
      now apply in_cll_times_r with (Δ := ∅) (Δ' := ∅).
    + now apply in_cll_plus_l.
    + now apply in_cll_plus_r1.
    + now apply in_cll_plus_r2.
    + apply in_cll_bot_l.
    + apply in_cll_top_r.
    + now apply in_cll_unit_l.
    + apply in_cll_unit_r.
  Qed.

End ill_cll_is_sound.

Section Schellinx_observation.

  (* This is an observation purely about cut-free CLL

      One cannot get a cut-free CLL proof of Γ ⊢ ∅
      unless ⟘ or 𝟘 or a negation occurs in Γ *)

  Let schellinx_rec Γ Δ :
               Γ ⊢c Δ
            -> Δ = ∅
            -> exists f, In f Γ /\ cll_has_bot_zero_neg f.
  Proof.
    induction 1 as [ A                                                        (* ax *)
                   | Γ Δ Γ' Δ' H1 H2 H3 IH3                                   (* perm *)
                   | Γ Δ A H1 IH1 | Γ Δ A H1 IH1                              (* negation *)
                   | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2 | Γ Δ A B H1 IH1             (* -o *)
                   | Γ Δ A B H1 IH1 | Γ Δ A B H1 IH1 | Γ Δ A B H1 IH1 H2 IH2  (* & *)
                   | Γ A B Δ H1 IH1 | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2             (* * *)
                   | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2 | Γ A B Δ H1 IH1             (* par *)
                   | Γ A B Δ H1 IH1 H2 IH2 | Γ A B Δ H1 IH1 | Γ A B Δ H1 IH1  (* + *)
                   | |                                                        (* bot, top *)
                   | Γ Δ H1 IH1 |                                             (* unit *)
                   | |                                                        (* zero *)
                   | Γ A Δ H1 IH1 | Γ A Δ H1 IH1                              (* bang *)
                   | Γ A Δ H1 IH1 |                                           (* qmrk *)
                   | Γ A Δ H1 IH1 |                                           (* weak *)
                   | Γ A Δ H1 IH1 | ];                                        (* cntr *)
              try discriminate.
    + intros ->.
      apply Permutation_sym, Permutation_nil in H2 as ->; auto.
      destruct IH3 as (f & G1 & G2); auto.
      exists f; split; auto.
      revert G1; now apply Permutation_in.
    + intros ->; exists (⊖A); simpl; auto.
    + intros H.
      app inv nil in H.
      destruct IH2 as (f & [ <- | ] & ?); auto.
      * exists (A ⊸ B); simpl; split; auto.
      * exists f; split; auto.
        right; apply in_or_app; tauto.
    + intros ->.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (A&B); simpl; auto.
      * exists f; simpl; auto.
    + intros ->.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (A&B); simpl; auto.
      * exists f; simpl; auto.
    + intros ->.
      destruct IH1 as (f & [ <- | [ <- | ] ] & ?); auto.
      * exists (A⊗B); simpl; auto.
      * exists (A⊗B); simpl; auto.
      * exists f; simpl; auto.
    + intros H.
      app inv nil in H.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (A⅋B); simpl; auto.
      * exists f; simpl; split; auto.
        rewrite in_app_iff; auto.
    + intros ->.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (A⊕B); simpl; auto.
      * exists f; simpl; auto.
    + exists ⟘; simpl; auto.
    + intros ->.
      destruct IH1 as (f & ? & ?); auto.
      exists f; simpl; auto.
    + exists 𝟘; simpl; auto.
    + intros ->.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (!A); simpl; auto.
      * exists f; simpl; auto.
    + destruct Δ; try discriminate; intros _ ; simpl in *.
      destruct IH1 as (f & [ <- | ] & ?); auto.
      * exists (‽A); simpl; auto.
      * exists f; simpl; auto.
    + intros ->.
      destruct IH1 as (f & ? & ?); auto.
      * exists f; simpl; auto.
    + intros ->.
      destruct IH1 as (f & [ <- | [ <- | ] ] & ?); auto.
      * exists (!A); simpl; auto.
      * exists (!A); simpl; auto.
      * exists f; simpl; auto.
  Qed.

  Lemma Schellinx_observation Γ :
          Γ ⊢c ∅ -> exists f, In f Γ /\ cll_has_bot_zero_neg f.
  Proof. intros; now apply schellinx_rec with (2 := eq_refl). Qed.

End Schellinx_observation.

Section cll_ill_soundness.

  (* If an ILL sequent Γ ⊢ A is cut-free CLL provable then
     it is also cut-free ILL provable unless it contains ⟘ *)

  (* A handy tactic for Forall goals ... *)

  Tactic Notation "solve" "Forall" :=
    repeat rewrite Forall_cons_inv in *;
    repeat rewrite Forall_app in *; simpl in *; tauto.

  Let cll_ill_rec Γ Δ A :
               Γ ⊢c Δ
            -> Δ = A::∅
            -> Forall from_ill (A::Γ)
            -> ⟪Γ⟫ ⊢i ⟨A⟩
            \/ cll_has_bot_zero_neg A
            \/ exists f, In f Γ /\ cll_has_bot_zero_neg f.
  Proof.
    intros H; revert H A.
    induction 1 as [ A                                                        (* ax *)
                   | Γ Δ Γ' Δ' H1 H2 H3 IH3                                   (* perm *)
                   | Γ Δ A H1 IH1 | Γ Δ A H1 IH1                              (* negation *)
                   | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2 | Γ Δ A B H1 IH1             (* -o *)
                   | Γ Δ A B H1 IH1 | Γ Δ A B H1 IH1 | Γ Δ A B H1 IH1 H2 IH2  (* & *)
                   | Γ A B Δ H1 IH1 | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2             (* * *)
                   | Γ Δ Γ' Δ' A B H1 IH1 H2 IH2 | Γ A B Δ H1 IH1             (* par *)
                   | Γ A B Δ H1 IH1 H2 IH2 | Γ A B Δ H1 IH1 | Γ A B Δ H1 IH1  (* + *)
                   | |                                                        (* bot, top *)
                   | Γ Δ H1 IH1 |                                             (* unit *)
                   | |                                                        (* zero *)
                   | Γ A Δ H1 IH1 | Γ A Δ H1 IH1                              (* bang *)
                   | Γ A Δ H1 IH1 |                                           (* qmrk *)
                   | Γ A Δ H1 IH1 |                                           (* weak *)
                   | Γ A Δ H1 IH1 | ];                                        (* cntr *)
               intros C HΔ HΓ.
    + inversion HΔ; left; simpl; constructor.
    + subst.
      apply Permutation_sym, Permutation_length_1_inv in H2 as ->.
      destruct (IH3 _ eq_refl) as [ H | [ | (f & H & ?) ] ]; auto.
      * rewrite Forall_cons_inv in *.
        destruct HΓ as (? & HΓ); split; auto.
        revert HΓ; apply Permutation_Forall, Permutation_sym; auto.
      * left; apply in_ill3_perm with (2 := H).
        now apply Permutation_map.
      * do 2 right; exists f; split; auto.
        revert H; now apply Permutation_in.
    + contradict HΓ; solve Forall.
    + inversion HΔ; subst; contradict HΓ; solve Forall.
    + app inv singleton in HΔ.
      * destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; auto.
        - solve Forall.
        - destruct (IH2 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; auto.
          ++ solve Forall.
          ++ left; simpl; rewrite map_app; constructor; auto.
          ++ do 2 right; exists (A⊸B); simpl; tauto.
          ++ do 2 right; exists f; split; auto; right; apply in_or_app; tauto.
        - do 2 right; exists (A⊸B); simpl; tauto.
        - do 2 right; exists f; split; auto; right; apply in_or_app; tauto.
      * apply Schellinx_observation in H2 as (f & [ <- | ] & ?).
        - do 2 right; exists (A⊸B); simpl; tauto.
        - do 2 right; exists f; split; auto; right; apply in_or_app; tauto.
    + inversion HΔ; subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; constructor; auto.
      * do 2 right; exists f; auto.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; apply in_ill3_with_l1; auto.
      * do 2 right; exists (A&B); simpl; tauto.
      * do 2 right; exists f; auto.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; apply in_ill3_with_l2; auto.
      * do 2 right; exists (A&B); simpl; tauto.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst; clear HΔ.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * destruct (IH2 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
        - solve Forall.
        - left; simpl; constructor; auto.
        - do 2 right; exists f; simpl; tauto.
      * do 2 right; exists f; simpl; tauto.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | [ <- | ] ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; constructor; auto.
      * do 2 right; exists (A⊗B); simpl; tauto.
      * do 2 right; exists (A⊗B); simpl; tauto.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst.
      app inv nil in H3.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * destruct (IH2 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
        - solve Forall.
        - left; rewrite map_app; constructor; auto.
        - do 2 right; exists f; split; auto.
          apply in_or_app; auto.
      * do 2 right; exists f; split; auto.
        apply in_or_app; auto.
    + contradict HΓ; solve Forall.
    + inversion HΔ; subst; contradict HΓ; solve Forall.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * destruct (IH2 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
        - solve Forall.
        - left; simpl; now constructor.
        - do 2 right; exists (A⊕B); simpl; tauto.
        - do 2 right; exists f; auto.
      * do 2 right; exists (A⊕B); simpl; tauto.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now apply in_ill3_plus_r1.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now apply in_ill3_plus_r2.
      * do 2 right; exists f; auto.
    + left; constructor.
    + inversion HΔ; subst; left; constructor.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now constructor.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst; left; constructor.
    + discriminate.
    + inversion HΔ; subst; contradict HΓ; solve Forall.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now constructor.
      * do 2 right; exists (!A); simpl; auto.
      * do 2 right; exists f; auto.
    + destruct Δ; try discriminate.
      inversion HΔ; subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; rewrite cll_ill_lbang in *; now constructor.
      * do 2 right; exists f; auto.
    + destruct Δ as [ |  D [ ] ]; try discriminate.
      inversion HΔ; subst; contradict HΓ; solve Forall.
    + inversion HΔ; subst; contradict HΓ; solve Forall.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & ? & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now constructor.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst.
      rewrite Forall_cons_inv in HΓ; simpl in HΓ; tauto.
    + subst.
      destruct (IH1 _ eq_refl) as [ ? | [ | (f & [ <- | [ <- | ] ] & ?) ] ]; simpl; auto.
      * solve Forall.
      * left; now constructor.
      * do 2 right; exists (!A); simpl; auto.
      * do 2 right; exists (!A); simpl; auto.
      * do 2 right; exists f; auto.
    + inversion HΔ; subst; contradict HΓ; solve Forall.
  Qed.

  Lemma cll_ill_soundness Γ A :
             ⟦Γ⟧ ⊢c [A]::∅
          -> Γ ⊢i A
          \/ ill_has_bot A
          \/ exists f, In f Γ /\ ill_has_bot f.
  Proof.
    intros H.
    apply cll_ill_rec with (2 := eq_refl) in H.
    * rewrite ill_cll_ill_list, ill_cll_ill, <- ill_cll_has_bot_eq in H.
      destruct H as [ | [ | (f & G1 & G2) ] ]; auto.
      do 2 right.
      apply in_map_iff in G1.
      destruct G1 as (g & <- & ?).
      exists g; rewrite ill_cll_has_bot_eq; auto.
    * rewrite -> Forall_map with (f := ill_cll) (ll := A::Γ), Forall_forall.
      intros; apply ill_cll_from_ill.
  Qed.

End cll_ill_soundness.

(* If the ILL sequent Γ ⊢ A does not contain any occurences of ⟘   then
   it is provable in ILL iff it is provable in CLL

   Which gives a direct reduction for CLL undecidability *)

Theorem ill_cll_equiv Γ A  :
          (forall f, In f (A::Γ) -> ~ ill_has_bot f)
       -> Γ ⊢i A <-> ⟦Γ⟧ ⊢c [A]::∅.
Proof.
  intros H; split.
  + apply ill_cll_soundness.
  + intros H1.
    apply cll_ill_soundness in H1 as [ | [ ? | (f & ? & ?) ] ]; auto.
    * destruct (H A); simpl; auto.
    * destruct (H f); simpl; auto.
Qed.

author: uds-psl

repo: coq-library-undecidability


text:
Require Import List.

Require Import InfSeqExt.infseq.
Require Import InfSeqExt.map.
Require Import InfSeqExt.exteq.

Require Import StructTact.StructTactics.
Require Import StructTact.Util.

Require Import Cheerios.Cheerios.

Require Import Chord.Chord.
Require Import Chord.ChordSerialized.
Require Import Chord.ChordSerializedSimulations.
(*
Require Import Chord.ChordStabilization.
Require Import Chord.SystemReachable.
Require Import Chord.SystemPointers.
Require Import Chord.QueriesEventuallyStop.

(* useful definitions and lemmas *)

Definition serialize_occurrence (occ : ChordSemantics.occurrence) :=
  {| occ_gst := serialize_global_state (ChordSemantics.occ_gst occ);
     occ_label := (ChordSemantics.occ_label occ) |}.

Definition revert_occurrence (occ : ChordSerializedSemantics.occurrence) :=
  {| ChordSemantics.occ_gst := revert_global_state (ChordSerializedSemantics.occ_gst occ);
     ChordSemantics.occ_label := (ChordSerializedSemantics.occ_label occ) |}.

Definition revert_serialize_occurrence o :=
  serialize_occurrence (revert_occurrence o).

Inductive reachable_st_serialized : global_state -> Prop :=
  reachableInitS : forall gst,
    initial_st (revert_global_state gst) -> reachable_st_serialized gst
| reachableStepS : forall gst gst',
    reachable_st_serialized gst ->
    ChordSerializedSemantics.step_dynamic gst gst' ->
    reachable_st_serialized gst'.

Lemma revert_reachable : forall ex : infseq occurrence,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    reachable_st (ChordSemantics.occ_gst (infseq.hd (map revert_occurrence ex))).
Proof.
  intros.
  destruct ex.
  simpl in *.
  induction H.
  - constructor.
    assumption.
  - eapply reachableStep; eauto.
    apply step_dynamic_serialized_step_dynamic.
    assumption.
Qed.

Lemma revert_lb_execution : forall ex,
    lb_execution ex ->
    ChordSemantics.lb_execution (map revert_occurrence ex).
Proof.
  cofix.
  intros.
  do 2 (destruct ex; rewrite map_Cons).
  constructor; inv H.
  - apply serialized_labeled_step_labeled_step.
    assumption.
  - rewrite <- map_Cons.
    apply revert_lb_execution.
    assumption.
Qed.

(* rewrite definitions for stabilization property *)
Definition live_node gst h :=
  In h (nodes gst) /\
  ~ In h (failed_nodes gst) /\
  (exists st : data, sigma gst h = Some st /\ joined st = true).

Definition correct_succs (gst : global_state) (h : pointer) (st : data) : Prop :=
  forall s xs ys s',
    wf_ptr h ->
    succ_list st = xs ++ s :: ys ->
    ptr_between h s' s ->
    live_node gst (addr_of s') ->
    wf_ptr s' ->
    In s' xs.

Definition better_pred (gst : global_state) (h p p' : pointer) : Prop :=
  wf_ptr h /\
  wf_ptr p /\
  wf_ptr p' /\
  live_node gst (addr_of p') /\
  ptr_between p p' h.

Definition pred_correct (gst : global_state) (h : pointer) (p : option pointer) : Prop :=
  exists p0,
    p = Some p0 /\
    forall p',
      p' <> p0 ->
      live_node gst (addr_of p') ->
      wf_ptr p' ->
      better_pred gst h p' p0.

Definition ideal (gst : global_state) : Prop :=
  forall h st,
    live_node gst (addr_of h) ->
    wf_ptr h ->
    sigma gst (addr_of h) = Some st ->
    correct_succs gst h st /\
    length (succ_list st) = Chord.SUCC_LIST_LEN /\
    pred_correct gst h (pred st).

(* more helper lemmas *)
Lemma revert_live_node : forall gst h, live_node (serialize_global_state gst) (addr_of h) ->
                                  ConstrainedChord.live_node gst (addr_of h).
Proof.
  intuition.
Qed.

Lemma preserves_ideal_gst : forall gst,
    ChordStabilization.ideal gst -> ideal (serialize_global_state gst).
Proof.
  unfold ChordStabilization.ideal, ideal.
  intros.
  apply H; assumption.
Qed.

Lemma serialize_ideal : forall occ,
    ChordStabilization.ideal (ChordSemantics.occ_gst occ) ->
    ideal (occ_gst (serialize_occurrence occ)).
Proof.
  destruct occ.
  simpl.
  apply preserves_ideal_gst.
Qed.

Lemma serialize_continuously_ideal : forall ex : infseq ChordSemantics.occurrence,
    continuously (now (fun o => ChordStabilization.ideal (ChordSemantics.occ_gst o))) ex ->
    continuously (now (fun o => ideal (occ_gst o)))
                 (map serialize_occurrence ex).
Proof.
  intros.
  eapply continuously_map; eauto.
  intros.
  destruct s. simpl in *.
  apply serialize_ideal.
  assumption.
Qed.

Lemma ideal_extensional : extensional (continuously (now (fun o => ideal (occ_gst o)))).
Proof.
  apply extensional_continuously.
  unfold extensional, now.
  intros.
  do 2 break_match.
  find_apply_lem_hyp exteq_inversion.
  break_and. subst_max.
  assumption.
Qed.

Definition blocked_by (gst : global_state) (s h : addr) : Prop :=
  In h (nodes gst) /\
  In s (nodes gst) /\
  exists st__h st__s dstp q m,
    sigma gst h = Some st__h /\
    sigma gst s = Some st__s /\
    cur_request st__h = Some (dstp, q, m) /\
    addr_of dstp = s /\
    In (h, m) (delayed_queries st__s).

Definition circular_wait occ :=
  has_cycle (blocked_by (occ_gst occ)).

Lemma revert_circular_wait : forall ex,
    always (~_ now circular_wait) ex ->
    always (~_ now QueriesEventuallyStop.circular_wait) (map revert_occurrence ex).
Proof.
  apply always_map.
  intros.
  eapply not_tl_map; eauto.
  unfold now. destruct s0.
  rewrite map_Cons.
  unfold QueriesEventuallyStop.circular_wait, circular_wait,
  QueriesEventuallyStop.blocked_by, blocked_by, has_cycle.
  intros. break_exists.
  eauto.
Qed.

Lemma revert_serialize_msgs : forall gst,
    serialize_global_state (revert_global_state gst) = gst ->
    List.map serialize_msg (List.map revert_msg (msgs gst)) = msgs gst.
Proof.
  unfold serialize_global_state, revert_global_state. simpl.
  intros.
  find_reverse_rewrite.
  simpl.
  rewrite serialize_revert_msgs.
  reflexivity.
Qed.

Lemma revert_serialize_trace : forall gst,
    serialize_global_state (revert_global_state gst) = gst ->
    List.map serialize_event
             (List.map revert_event (trace gst)) = trace gst.
Proof.
  destruct gst.
  unfold serialize_global_state, revert_global_state. simpl.
  intros.
  find_inversion.
  rewrite serialize_revert_events.
  reflexivity.
Qed.

Lemma serialize_send_revert_serialize : forall l h,
  List.map serialize_event
    (List.map revert_event
       (List.map e_send (List.map serialize_msg (List.map (ChordSemantics.send h) l)))) =
  List.map e_send (List.map serialize_msg (List.map (ChordSemantics.send h) l)).
Proof.
  induction l.
  - reflexivity.
  - intros.
    simpl. repeat break_let.
    unfold revert_msg, revert_payload.
    rewrite serialize_deserialize_top_id.
    rewrite IHl.
    reflexivity.
Qed.

Lemma revert_serialize_start_handler_msgs : forall h k d l0 l,
    start_handler h (k :: nil) = (d, l0, l) ->
    List.map serialize_msg (List.map revert_msg (List.map (send h) l0))
    = List.map (send h) l0.
Proof.
  unfold start_handler.
  intros. repeat break_let.
  find_inversion.
  rewrite map_send_serialize.
  rewrite serialize_revert_msgs.
  reflexivity.
Qed.

Lemma revert_serialize_start_handler_events : forall h k d l0 l,
    start_handler h (k :: nil) = (d, l0, l) ->
    List.map serialize_event
             (List.map revert_event (List.map e_send (List.map (send h) l0))) =
    List.map e_send (List.map (send h) l0).
Proof.
  unfold start_handler.
  intros. repeat break_let.
  find_inversion.
  rewrite map_send_serialize.
  rewrite serialize_send_revert_serialize.
  reflexivity.
Qed.

Lemma revert_serialize_timeout_handler : forall h st t st' ms newts clearedts,
      timeout_handler h st t = (st', ms, newts, clearedts) ->
      List.map serialize_msg (List.map revert_msg (List.map (send h) ms)) = List.map (send h) ms.
Proof.
  unfold timeout_handler, serialize_res.
  intros.
  repeat break_let.
  find_inversion.
  rewrite map_send_serialize.
  rewrite serialize_revert_msgs.
  reflexivity.
Qed.

Lemma revert_serialize_recv_handler : forall a0 a1 d p st ms newts clearedts,
      recv_handler a0 a1 d p = (st, ms, newts, clearedts) ->
      List.map serialize_msg (List.map revert_msg (List.map (send a1) ms)) = List.map (send a1) ms.
Proof.
  unfold recv_handler, serialize_res.
  intros.
  repeat break_let.
  find_inversion.
  rewrite map_send_serialize.
  rewrite serialize_revert_msgs.
  reflexivity.
Qed.

Lemma revert_serialize_msgs_l_aux : forall xs m ys,
    List.map serialize_msg (List.map revert_msg (xs ++ m :: ys)) = xs ++ m :: ys ->
    List.map serialize_msg (List.map revert_msg xs) = xs.
Proof.
  induction xs.
  - reflexivity.
  - intros. simpl.
    rewrite (IHxs m ys); inversion H.
    + repeat find_rewrite.
      reflexivity.
    + simpl in *.
      repeat find_rewrite.
      reflexivity.
Qed.

Lemma revert_serialize_msgs_mid_aux : forall xs m ys,
    List.map serialize_msg (List.map revert_msg (xs ++ m :: ys)) = xs ++ m :: ys ->
    serialize_msg (revert_msg m) = m.
Proof.
  induction xs.
  - simpl. intros.
    inversion H.
    repeat find_rewrite.
    reflexivity.
  - intros. simpl.
    rewrite (IHxs m ys); inversion H.
    + repeat find_rewrite.
      reflexivity.
    + simpl in *.
      repeat find_rewrite.
      reflexivity.
Qed.

Lemma revert_serialize_msgs_r_aux : forall xs m ys,
    List.map serialize_msg (List.map revert_msg (xs ++ m :: ys)) = xs ++ m :: ys ->
    List.map serialize_msg (List.map revert_msg ys) = ys.
Proof.
  induction xs.
  - simpl. intros.
    inversion H.
    repeat find_rewrite.
    reflexivity.
  - intros. simpl.
    rewrite (IHxs m ys); inversion H.
    + repeat find_rewrite.
      reflexivity.
    + simpl in *.
      repeat find_rewrite.
      reflexivity.
Qed.

Lemma revert_serialize_msgs_l : forall gst xs m ys,
  serialize_global_state (revert_global_state gst) = gst ->
      msgs gst = xs ++ m :: ys ->
      List.map serialize_msg (List.map revert_msg xs) = xs.
Proof.
  unfold serialize_global_state, revert_global_state. simpl in *.
  intros.
  destruct gst. simpl in *.
  find_inversion.
  erewrite revert_serialize_msgs_l_aux; eauto.
Qed.

Lemma revert_serialize_msgs_mid : forall gst xs m ys,
  serialize_global_state (revert_global_state gst) = gst ->
      msgs gst = xs ++ m :: ys ->
      serialize_msg (revert_msg m) = m.
Proof.
  unfold serialize_global_state, revert_global_state. simpl in *.
  intros.
  destruct gst. simpl in *.
  find_inversion.
  erewrite revert_serialize_msgs_mid_aux; eauto.
Qed.

Lemma revert_serialize_msgs_r : forall gst xs m ys,
  serialize_global_state (revert_global_state gst) = gst ->
      msgs gst = xs ++ m :: ys ->
      List.map serialize_msg (List.map revert_msg ys) = ys.
Proof.
  unfold serialize_global_state, revert_global_state. simpl in *.
  intros.
  destruct gst. simpl in *.
  find_inversion.
  erewrite revert_serialize_msgs_r_aux; eauto.
Qed.

Lemma reachable_revert_serialize_global_state : forall gst,
    reachable_st_serialized gst ->
    serialize_global_state (revert_global_state gst) = gst.
Proof.
  intros.
  induction H.
  - unfold initial_st in H.
    intuition.
    unfold serialize_global_state, revert_global_state.
    destruct gst. simpl in *.
    do 2 find_apply_lem_hyp map_eq_nil.
    subst_max.
    reflexivity.
  - inv_prop step_dynamic;
      subst_max.
    + unfold update_for_start. repeat break_let.
      unfold serialize_global_state, revert_global_state. simpl.
      repeat rewrite map_app.
      erewrite revert_serialize_start_handler_msgs;
        eauto.
      erewrite revert_serialize_start_handler_events;
        eauto.
      rewrite revert_serialize_msgs; try assumption.
      rewrite revert_serialize_trace; try assumption.
      reflexivity.
    + unfold fail_node.
      unfold serialize_global_state, revert_global_state. simpl.
      rewrite revert_serialize_msgs; try assumption.
      rewrite revert_serialize_trace; try assumption.
      reflexivity.
    + unfold apply_handler_result, serialize_global_state, revert_global_state.
      simpl.
      repeat rewrite map_app.
      erewrite revert_serialize_timeout_handler;
        eauto.
      rewrite revert_serialize_msgs; try assumption.
      rewrite revert_serialize_trace; try assumption.
      reflexivity.
    + unfold apply_handler_result, serialize_global_state, revert_global_state.
      simpl.
      repeat rewrite map_app.
      rewrite (revert_serialize_msgs_l gst xs m ys) at 1; try assumption.
      rewrite (revert_serialize_msgs_r gst xs m ys) at 1; try assumption.
      erewrite revert_serialize_trace; eauto.
      simpl.
      erewrite revert_serialize_msgs_mid; eauto.
      destruct m. destruct p. simpl in *.
      erewrite revert_serialize_recv_handler; eauto.
    + unfold update_msgs_and_trace, serialize_global_state, revert_global_state.
      simpl.
      repeat rewrite map_app.
      erewrite revert_serialize_msgs; eauto.
      erewrite revert_serialize_trace; eauto.
      simpl.
      unfold client_payload in *. break_exists. intuition.
      unfold revert_payload.
      match goal with
      | H : serialize_top _ = _ |- _ => rewrite <- H
      end.
      rewrite serialize_deserialize_top_id.
      reflexivity.
    + unfold update_msgs_and_trace, serialize_global_state, revert_global_state.
      simpl.
      repeat rewrite map_app. simpl.
      erewrite revert_serialize_msgs_l; eauto.
      erewrite revert_serialize_msgs_mid; eauto.
      erewrite revert_serialize_msgs_r; eauto.
      erewrite revert_serialize_trace; eauto.
Qed.

Lemma revert_serialize_exteq : forall ex,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    lb_execution ex ->
    exteq (map serialize_occurrence (map revert_occurrence ex)) ex.
Proof.
  cofix.
  intros.
  destruct ex. do 2 rewrite map_Cons.
  unfold serialize_occurrence, revert_occurrence. simpl.
  erewrite reachable_revert_serialize_global_state; eauto.
  destruct o.
  constructor.
  apply revert_serialize_exteq.
  - destruct ex. simpl in *.
    inv_prop lb_execution.
    eapply reachableStepS; eauto.
    eapply labeled_step_is_unlabeled_step; eauto.
  - eapply lb_execution_invar; eauto.
Qed.

Lemma reachable_enabled' : forall l o,
    ChordSemantics.l_enabled l o -> l_enabled l (serialize_occurrence o).
Proof.
  unfold ChordSemantics.l_enabled, ChordSemantics.enabled, l_enabled, enabled.
  intros.
  break_exists.
  exists (serialize_global_state x).
  apply labeled_step_serialized_labeled_step.
  assumption.
Qed.

Lemma lb_execution_enabled : forall ex l,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    lb_execution ex ->
    eventually (now (ChordSemantics.l_enabled l)) (map revert_occurrence ex) ->
    eventually (now (l_enabled l)) ex.
Proof.
  intros.
  assert (G : extensional (eventually (now (l_enabled l)))).
  { apply extensional_eventually.
    unfold extensional.
    intros.
    destruct s1, s2.
    inv_prop exteq.
     subst_max.
    unfold now in *. repeat break_match.
    assumption. }
  unfold extensional in *.
  apply (G (map serialize_occurrence (map revert_occurrence ex))).
  - eapply revert_serialize_exteq; eauto.
  - eapply eventually_map; eauto.
    intros.
    destruct s. simpl in *.
    apply reachable_enabled'.
    assumption.
Qed.

Lemma revert_always_eventually_enabled : forall ex l,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    lb_execution ex ->
    always (eventually (now (ChordSemantics.l_enabled l))) (map revert_occurrence ex) ->
    always (eventually (now (l_enabled l))) ex.
Proof.
  cofix.
  constructor.
  - inv_prop always.
    apply lb_execution_enabled; assumption.
  - destruct ex. rewrite map_Cons in *.
    apply revert_always_eventually_enabled.
    + simpl.
      destruct ex.
      simpl in *.
      inv_prop lb_execution. simpl in *.
      eapply reachableStepS; eauto.
      * eapply labeled_step_is_unlabeled_step. eauto.
      * eapply lb_execution_invar. eauto.
    + inv_prop always.
      assumption.
Qed.

Lemma revert_strong_local_fairness : forall ex,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    lb_execution ex ->
    strong_local_fairness ex ->
    ChordSemantics.strong_local_fairness (map revert_occurrence ex).
Proof.
  unfold strong_local_fairness, ChordSemantics.strong_local_fairness.
  intros.
  assert (inf_occurred l ex).
  - match goal with
    | H : context[inf_occurred] |- _ => apply H
    end.
    unfold inf_enabled, inf_often.
    unfold ChordSemantics.inf_enabled, inf_often in *.
    apply revert_always_eventually_enabled;
      assumption.
  - unfold ChordSemantics.inf_occurred, inf_often.
    unfold inf_occurred, inf_often in *.
    eapply always_map; eauto.
    intros.
    eapply eventually_map; eauto.
    unfold occurred, ChordSemantics.occurred.
    destruct s0. rewrite map_Cons.
    tauto.
Qed.

(* top-level correctness property *)
Theorem chord_serialized_stabilization :
  forall ex : infseq.infseq occurrence,
    reachable_st_serialized (occ_gst (infseq.hd ex)) ->
    lb_execution ex ->
    strong_local_fairness ex ->
    always (~_ (now circular_wait)) ex ->
    continuously (now (fun o => ideal (occ_gst o))) ex.
Proof.
  intros.
  match goal with
  | _ : _ |- continuously ?P _ =>
    assert (G : extensional (continuously P)) by (exact ideal_extensional)
  end.
  unfold extensional in G.
  apply (G (map serialize_occurrence (map revert_occurrence ex))).
  - eapply revert_serialize_exteq; eauto.
  - apply serialize_continuously_ideal.
    apply ChordStabilization.chord_stabilization.
    + apply revert_reachable.
      assumption.
    + apply revert_lb_execution.
      assumption.
    + apply revert_strong_local_fairness;
        assumption.
    + apply revert_circular_wait. assumption.
Qed.
*)

author: DistributedComponents

repo: verdi-chord


text:
(* Stack with Helping example from the course notes. *)

(* Contains definitions of the weakest precondition assertion, and its basic rules. *)
From iris.program_logic Require Export weakestpre.

(* Instantiation of Iris with the particular language. The notation file
   contains many shorthand notations for the programming language constructs, and
   the lang file contains the actual language syntax. *)
From iris.heap_lang Require Export notation lang.

(* Files related to the interactive proof mode. The first import includes the
   general tactics of the proof mode. The second provides some more specialized
   tactics particular to the instantiation of Iris to a particular programming
   language. *)
From iris.proofmode Require Export tactics.
From iris.heap_lang Require Import proofmode.

(* Definition of invariants and their rules (expressed using the fancy update modality). *)
From iris.base_logic.lib Require Export invariants.

(* The exclusive resource algebra. *)
From iris.algebra Require Import excl.

Context `{!heapG Σ}.
Context `{inG Σ (exclR unitR)}.

Notation iProp := (iProp Σ).

Section offers.

  (*
    An offer is a pair (v, l), where l is a location indicating the status of the offer:
      - 0: this is the initial offer state, when it hasn't been accepted or revoked.
      - 1: this offer has already been accepted by another thread
      - 2: the offer has been revoked by the thread that issued it
   *)

  (* Returns an offer containing the given value *)
  Definition mk_offer : val := λ: "v", ("v", ref #0).

  (* Given an offer (v, _), returns either (Some v) if the offer could be revoked (which
     happens if the offer state is 0), or None otherwise. Sets the offer state to 2. *)
  Definition revoke_offer : val :=
    λ: "off",
      let: "v" := Fst "off" in
      let: "l" := Snd "off" in
      if: (CAS "l" #0 #2) then SOME "v" else NONE.

  (* Given an offer (v, _), return either (Some v) if the offer could be accepted, or None
     otherwise. Mutates the offer state to 1. *)
  Definition accept_offer : val :=
    λ: "off",
      let: "v" := Fst "off" in
      let: "l" := Snd "off" in
      if: (CAS "l" #0 #1) then SOME "v" else NONE.

  (* Offer specification *)

  Variable Φ : val -> iProp. (* The predicate satisfied by the value in the offer. *)

  (* The key to revoking offer γ *)
  Definition offer_key γ := own γ (Excl ()).

  (* The following `stages` predicate describes the possible states of the lock
     (and will be later wrapped in an invariant). *)

  Definition stages (v : val) (l : loc) (γ : gname) : iProp :=
    (l ↦ #0 ∗ Φ v) ∨ (l ↦ #1) ∨ (l ↦ #2 ∗ offer_key γ).

  (* The representation predicate for offers. *)
  Definition is_offer (o : val) (γ : gname) : iProp :=
    (∃ (l : loc ) v, ⌜o = (v, #l)%V⌝ ∗ ∃ n, inv n (stages v l γ))%I.

  (* Method specifications *)
  Definition offer_inv : namespace := nroot .@ "offer_inv".

  (* When we create an offer, we get the offer and also the key to revoke it. *)
  Lemma wp_mk_offer v :
    {{{ Φ v }}} mk_offer v {{{ o, RET o; ∃ γ, (offer_key γ) ∗ (is_offer o γ) }}}.
  Proof.
    iIntros (P) "Hpre Hpost".
    iMod (own_alloc (Excl ())) as (γ) "Hown". { constructor. }
    iApply wp_fupd. rewrite /mk_offer. wp_pures. wp_alloc l as "Hl". wp_pures. iApply "Hpost".
    rewrite /is_offer. iExists γ. iFrame. iExists l, v. iSplitL "".
    { by iPureIntro. }
    iExists offer_inv. iApply (inv_alloc offer_inv  _ (stages v l γ)).
    iNext. rewrite /stages. iLeft. iFrame.
  Qed.

  (* To revoke an offer, we need its key. *)
  Lemma wp_revoke_offer o γ :
    {{{ is_offer o γ ∗ offer_key γ }}} revoke_offer o {{{ r, RET r; ∃ (v : val ), ⌜r = NONEV⌝ ∨ ⌜r = SOMEV v⌝ ∗ Φ v }}}.
  Proof.
    iIntros (P) "Hpre Hpost".
    rewrite /revoke_offer. wp_pures.
    iDestruct "Hpre" as "[Hpre Hkey]". iDestruct "Hpre" as (l v) "[-> Hpre]".
    iDestruct "Hpre" as (N) "Hpre".
    wp_pures. wp_bind (CmpXchg _ _ _).
    iInv N as "[[> Hl0 HΦ ] | [> Hl1 | [> Hl2 Hghost ]]]" "Hclose".
    - wp_cmpxchg_suc. iMod ("Hclose" with "[Hl0 Hkey]") as "_".
      { iNext. rewrite /stages. iRight. iRight. iFrame. }
      iModIntro. wp_pures.
      iApply "Hpost". iExists v. iRight. iFrame. by iPureIntro.
    - wp_cmpxchg_fail. iMod ("Hclose" with "[Hl1 Hkey]") as "_".
      { iNext. rewrite /stages. iRight. iLeft. iFrame. }
      iModIntro. wp_pures. iApply "Hpost". iExists #(). by iLeft.
    - wp_cmpxchg_fail. iMod ("Hclose" with "[Hl2 Hkey]") as "_".
      { iNext. rewrite /stages. iRight. iRight. iFrame. }
      iModIntro. wp_pures. iApply "Hpost". iExists #(). by iLeft.
  Qed.

  Lemma wp_accept_offer o γ :
    {{{ is_offer o γ }}} accept_offer o {{{ r, RET r; ∃ v, ⌜r = NONEV⌝ ∨ ⌜r = SOMEV v⌝ ∗ Φ v }}}.
    iIntros (P) "Hpre Hpost".
    rewrite /accept_offer. wp_pures.
    iDestruct "Hpre" as (l v) "[-> Hpre]". iDestruct "Hpre" as (N) "Hpre".
    wp_pures. wp_bind (CmpXchg _ _ _).
    iInv N as "[[> Hl0 HΦ ] | [> Hl1 | [> Hl2 Hghost ]]]" "Hclose".
    - wp_cmpxchg_suc. iMod ("Hclose" with "[Hl0]") as "_".
      { iNext. rewrite /stages. iRight. iLeft. iFrame. }
      iModIntro. wp_pures.
      iApply "Hpost". iExists v. iRight. iFrame. by iPureIntro.
    - wp_cmpxchg_fail. iMod ("Hclose" with "[Hl1]") as "_".
      { iNext. rewrite /stages. iRight. iLeft. iFrame. }
      iModIntro. wp_pures. iApply "Hpost". iExists #(). by iLeft.
    - wp_cmpxchg_fail. iMod ("Hclose" with "[Hl2 Hghost]") as "_".
      { iNext. rewrite /stages. iRight. iRight. iFrame. }
      iModIntro. wp_pures. iApply "Hpost". iExists #(). by iLeft.
  Qed.

End offers.

Section mailbox.

  (* Returns a pair of two closures: the first component is for putting an offer in the mailbox
     The second is for getting an offer out of the mailbox. *)
  Definition mk_mailbox : val :=
    λ: <>,
       let: "r" := ref NONEV in

       (* Returns (Some v) if the element was not taken by someone else, or None if
          another thread accepted the offer. *)
       let: "put" :=
         (λ: "v",
           let: "o" := mk_offer "v" in
           "r" <- SOME "o";;
           revoke_offer "o")
       in

       (* Returns (Some v) if we were able to get an element from the mailbox, and
          None otherwise. *)
       let: "get" :=
         (λ: "v",
           match: !"r" with
             NONE => NONEV
           | SOME "o" => accept_offer "o"
           end)
       in

       ("put", "get").

  (* Specs *)

  Variable Φ : val -> iProp.

  (* Representation predicate for mailboxes *)
  Definition is_mailbox (m : loc) : iProp :=
    m ↦ NONEV ∨ (∃ (o : val) γ, m ↦ SOMEV o ∗ is_offer Φ o γ).

  Definition mailbox_inv : namespace := nroot .@ "mailbox_inv".

  (* Since mk_mailbox returns a pair of closures, its specification uses nested Hoare triples *)
  Lemma wp_mk_mailbox :
    {{{ True }}} mk_mailbox #() {{{m, RET m; ∃ (put get : val),
                                   ⌜m = (put, get)%V⌝ ∗
                                   ∀ (v : val), {{{ Φ v }}} put v {{{ vr, RET vr; ⌜vr = NONEV⌝ ∨ ∃ vv : val, ⌜vr = SOMEV vv⌝ ∗ Φ vv }}} ∗
                                   {{{ True }}} get #()  {{{ r, RET r; ⌜r = NONEV⌝ ∨ ∃ (v : val), ⌜r = SOMEV v⌝ ∗ Φ v }}}
                             }}}.
  Proof.
    iIntros (P) "_ Hpost".
    rewrite /mk_mailbox. wp_pures. wp_alloc r as "Hr". wp_pure _.
    iMod (inv_alloc mailbox_inv _ (is_mailbox r) with "[Hr]") as "#Hinv".
    { iNext. rewrite /is_mailbox. by iLeft; iFrame. }
    wp_pures.
    iApply "Hpost". iExists _, _. iSplitL "".
    { by iPureIntro. }
    iIntros (v).
    iSplitL "".
    - iModIntro. iIntros (Cont) "Hpre Hpost".
      wp_pures. wp_apply (wp_mk_offer Φ v with "Hpre").
      iIntros (o) "Ho". iDestruct "Ho" as (γ) "[Hkey #Ho]". wp_pures.
      wp_bind (_ <- _)%E. rewrite /is_mailbox.
      iInv mailbox_inv as "[> Hnone | Hsome]" "Hclose".
      * wp_store. iMod ("Hclose" with "[Ho Hnone]") as "_".
        { iNext. iRight. iExists o, γ. iFrame "#". iFrame. }
        iModIntro. wp_pures. wp_apply (wp_revoke_offer Φ o γ with "[Hkey]"); auto.
        iIntros (r0) "Hst". iApply "Hpost".
        iDestruct "Hst" as (v0) "[Hnone | Hsome]".
        { by iLeft. }
        { by iRight; iExists v0. }
      * iDestruct "Hsome" as (o0 γ0) "[Hr _]".
        wp_store. iMod ("Hclose" with "[Hr]") as "_".
        { iNext. by iRight; iExists o, γ; iFrame. }
        iModIntro. wp_pures. wp_apply (wp_revoke_offer Φ o γ with "[Hkey]").
        { iFrame; iFrame "#". }
        iIntros (r0) "Hpre". iDestruct "Hpre" as (v0) "Hpre".
        iApply "Hpost". iDestruct "Hpre" as "[Hnone | Hsome]".
        { by iLeft. }
        { by iRight; iExists v0. }

    - iModIntro. iIntros (P') "_ Hpost".
      wp_pures. wp_bind (! _)%E.
      iInv mailbox_inv as "[Hnone | Hsome]" "Hclose".
      * wp_load. iMod ("Hclose" with "[Hnone]") as "_".
        {  iNext. rewrite /is_mailbox. by iLeft. }
        iModIntro. wp_pures. iApply "Hpost". by iLeft.
      * iDestruct "Hsome" as (o γ) "[Hr #Ho]".
        wp_load. iMod ("Hclose" with "[Hr]") as "_".
        { iNext. iRight. iExists o, γ. iFrame. iFrame "#". }
        iModIntro. wp_pures. wp_apply (wp_accept_offer Φ o γ); auto.
        iIntros (r0) "H". iApply "Hpost". iDestruct "H" as (v0) "[Hnone | Hsome]".
        { by iLeft. }
        { by iRight; iExists v0. }
  Qed.

End mailbox.

Section stack.

  Definition mk_stack : val :=
    λ: <>,
       let: "mb" := mk_mailbox #() in
       let: "put" := Fst "mb" in
       let: "get" := Snd "mb" in

       (* The stack is a pointer p that points to either
          - NONEV, if the stack is empty
          - SOMEV l, if the stack is non-empty.
            l in turn points to a pair (h, t), where h is the top of the stack
            and `t` is the rest of the stack. *)

       (* TODO: explain how this differs from the course notes because of limitations
          on what can be compared with CAS. *)

       let: "stack" := ref NONEV in

       (* Push an element into the stack. Returns unit. *)
       let: "push" :=
          rec: "push" "v" :=
            match: ("put" "v") with
              NONE => #()
            | SOME "v" =>
              let: "curr" := !"stack" in
              let: "nstack" := SOME (ref ("v", "curr")) in
              if: (CAS "stack" "curr" "nstack") then #() else ("push" "v")
            end
       in

       (* Pop an element from the stack. If the stack is empty, return None,
          otherwise return Some head. *)
       let: "pop" :=
        rec: "pop" <> :=
          match: ("get" #()) with
            SOME "v" => SOME "v"
          | NONE =>
            match: !"stack" with
              NONE => NONEV
            | SOME "l" =>
              let: "p" := !"l" in
              let: "head" := Fst "p" in
              let: "tail" := Snd "p" in
              if: (CAS "stack" (SOME "l") "tail") then SOME "head" else ("pop" #())
            end
          end

       in

       ("push", "pop").

  (* Bag specification for mk_stack *)

  Variable Φ : val -> iProp.

  Definition oloc_to_val (o : option loc) : val :=
    match o with
      None => NONEV
    | Some l => SOMEV #l
    end.

  Local Notation "l ↦{-} v" := (∃ q, l ↦{q} v)%I
   (at level 20, format "l  ↦{-}  v") : bi_scope.

  Lemma partial_mapsto_duplicable l v :
    l ↦{-} v -∗ l ↦{-} v ∗ l ↦{-} v.
  Proof.
    iIntros "H". iDestruct "H" as (?) "[H1 H2]". iSplitL "H1"; eauto.
  Qed.

  (* The representation predicate for stacks. The version in the notes uses guarded
     recursion, but let's see if we can get by with a simpler version. *)
  Fixpoint is_stack (o : option loc) (ls : list val) : iProp :=
    match ls with
      nil => ⌜o = None⌝
    | x :: xs => ∃ (l : loc) (o' : option loc),
      ⌜o = Some l⌝ ∗ l ↦{-} (x, oloc_to_val o')%V ∗ Φ x ∗ (is_stack o' xs)
  end.

  Lemma is_stack_readonly_dup o ls : is_stack o ls -∗ is_stack o ls ∗
                                              (match ls with
                                                 nil => True
                                               | x :: xs =>  ∃ (l : loc) (o' : option loc),
                                                 ⌜o = Some l⌝ ∗ l ↦{-} (x, oloc_to_val o')%V
                                               end)%I.
  Proof.
    iIntros "Hs".
    destruct ls; auto.
    iSimpl in "Hs".
    iDestruct "Hs" as (???) "[H1 H2]".
    iDestruct (partial_mapsto_duplicable with "H1") as "[H1 H1']".
    iSplitR "H1'"; subst;  iExists H0, H1; iFrame; iPureIntro; done.
  Qed.

  Definition stack_inv (l : loc) : iProp :=
    ∃ (o : option loc) (ls : list val), l ↦ oloc_to_val o ∗ is_stack o ls.

  Definition inv_ns : namespace := nroot .@ "stack_inv".

  Lemma oloc_to_val_unboxed ol : val_is_unboxed (oloc_to_val ol).
  Proof.
    rewrite /val_is_unboxed. destruct ol; simpl; auto.
  Qed.

  Lemma wp_mk_stack :
    {{{ True }}} mk_stack #() {{{ s, RET s; ∃ (push pop : val),
                                 ⌜s = (push, pop)%V⌝ ∗
                                                 (∀ (v : val), {{{ Φ v }}} push v {{{ RET #(); True
                                                                                }}}) ∗
                                                 ({{{ True }}} pop #() {{{ v, RET v; ⌜v = NONEV⌝ ∨ ∃ (w : val), ⌜v = SOMEV w⌝ ∗ Φ w }}})  }}}.
 Proof.
   iIntros (C) "Hpre Hpost".
   rewrite /mk_stack. wp_pures.
   wp_apply wp_mk_mailbox; try done.
   iIntros (m) "Hm". iDestruct "Hm" as (put get) "[-> #Hm]".
   wp_pures. wp_alloc s as "Hs".
   iMod (inv_alloc inv_ns _ (stack_inv s) with "[Hs]") as "#Hinv".
   { iNext. rewrite /stack_inv.
     iExists None, nil. iSimpl. iFrame. iPureIntro. reflexivity. }
   wp_pures. iApply "Hpost". iExists _, _.
   iSplitL "". auto.
   iSplitL "".

   (* push *)
   - iLöb as "Hind".
     iIntros (v). iModIntro.
     iIntros (C2) "Hpre Hpost".
     wp_pures. wp_bind (put _). iSpecialize ("Hm" $! v). iDestruct "Hm" as "[Hput _]".
     wp_apply ("Hput" with "Hpre").
     iIntros (vr) "Hpre".
     iDestruct "Hpre" as "[-> | Hsome]".
     { wp_pures. by iApply "Hpost". }
     iDestruct "Hsome" as (vv) "[-> HΦ]".
     wp_pures. wp_bind (! _)%E.
     iInv inv_ns as (ol ls) "[Hs His]" "Hclose". wp_load.
     iMod ("Hclose" with "[His Hs]") as "_".
     { iNext. rewrite /stack_inv. iExists ol, ls. iFrame. }
     iModIntro. wp_pures. wp_alloc l2 as "Hl2". wp_pures. wp_bind (CmpXchg _ _ _).
     iInv inv_ns as (ol2 ls2) "[Hs His]" "Hclose".
     destruct (decide (ol = ol2)); subst.
     + wp_cmpxchg_suc. { left; apply oloc_to_val_unboxed. }
       iMod ("Hclose" with "[Hs His Hl2 HΦ]") as "_". {
         iNext. rewrite /stack_inv.
         iExists (Some l2), (vv :: ls2).
         iFrame. rewrite /is_stack. iExists l2, ol2.
         iFrame. iSplitL "". iPureIntro. reflexivity.
         iExists 1%Qp. iFrame.
       }
       iModIntro. wp_pures. by (iApply "Hpost").
     + wp_cmpxchg_fail.
       { destruct ol, ol2; auto.
         simpl. intros eq. apply n. inversion eq; subst. reflexivity. }
       { left; apply oloc_to_val_unboxed. }
       iMod ("Hclose" with "[Hs His]") as "_". {
         iNext. rewrite /stack_inv. iExists ol2, ls2. iFrame.
       }
       iModIntro. wp_pure _. wp_pure _. iApply ("Hind" with "[HΦ]"); iFrame.

   (* pop *)
   - iLöb as "Hind".
     iIntros (v). iModIntro.
     iIntros "_ Hpost".
     wp_pures. wp_bind (get _). iSpecialize ("Hm" $! #()). iDestruct "Hm" as "[_ Hget]".
     wp_apply "Hget"; try done.
     iIntros (r) "[-> | Hs]".
     + wp_pures. wp_bind (! _)%E.
       iInv inv_ns as (ol ls) "[Hs His]" "Hclose". wp_load.

       iPoseProof (is_stack_readonly_dup ol ls with "His") as "[His Hmatch]".
       destruct ls.
       { rewrite /is_stack. iDestruct "His" as "->".
         iMod ("Hclose" with "[Hs]") as "_".
         { iNext. rewrite /stack_inv. iExists None, nil. iFrame. done. }
         iModIntro. wp_pures. iApply "Hpost". iLeft. iPureIntro; done.
       }

       iMod ("Hclose" with "[Hs His]") as "_".
       { iNext. rewrite /stack_inv. iExists ol, (v0 :: ls). iFrame. }
       iModIntro.
       iDestruct "Hmatch" as (???) "Hl". subst.

       wp_pures. iDestruct "Hl" as (q) "Hl".
       wp_load. wp_pures. wp_bind (CmpXchg _ _ _).

       iInv inv_ns as (ol ls2) "[Hs His]" "Hclose".
       destruct ol.
       * iSimpl in "Hs".
         destruct (decide (l = H0)).
         ** wp_cmpxchg_suc. destruct ls2.
            { iExFalso. iSimpl in "His". iDestruct "His" as %Heq. inversion Heq. }
            iSimpl in "His". iDestruct "His" as (???) "[H1 [H2 H3]]".
            inversion H4. subst.
            iAssert (⌜v0 = v1⌝ ∗ ⌜H1 = H3⌝)%I with "[Hl H1]" as "[-> ->]". {
              iDestruct "H1" as (q2) "H1".
              iDestruct (mapsto_agree with "Hl H1") as "%". simplify_eq.
              iSplitL "".
              { iPureIntro; done. }
              iPureIntro.
              destruct H1, H3; simpl in H5; inversion H5; auto.
            }
            iMod ("Hclose" with "[Hs H3]") as "_".
            { iNext. rewrite /stack_inv. iExists H3. subst.
              iExists ls2. iFrame.
            }
            iModIntro. wp_pures. iApply "Hpost".
            iRight. iExists v1. iSplitL ""; done.
         ** wp_cmpxchg_fail.
            iMod ("Hclose" with "[Hs His]") as "_".
            { iNext. rewrite /stack_inv. iExists (Some l), ls2. iFrame. }
            iModIntro. wp_pure _. wp_pure _. iApply "Hind"; auto.

       * wp_cmpxchg_fail.
         iMod ("Hclose" with "[Hs His]") as "_".
         { iNext. rewrite /stack_inv. iExists None, ls2. iFrame. }
         iModIntro. wp_pure _. wp_pure _. iApply "Hind"; auto.

     + iDestruct "Hs" as (v0) "[-> HΦ]".
       wp_pures. iApply "Hpost". iRight. iExists v0; iFrame. iPureIntro; done.
 Qed.

End stack.

author: abeln

repo: iris-practice

save_path: github-repos/coq/abeln-iris-practice


text:
Require Import ssreflect Setoid.

Class equiv_on (T : Type) :=
  {
    equiv_rel : T -> T -> Prop;
    equiv_rel_is_equiv : Equivalence equiv_rel
  }.
Arguments equiv_rel _ {_} _ _.
Existing Instance equiv_rel_is_equiv.

Notation "a ≡{ T } b" := (@equiv_rel T _ a b) (at level 70).

Instance ext_equiv {A B} `{equiv_on B} : equiv_on (A -> B).
Proof.
  exists (fun (f1 : A -> B) (f2 : A -> B) => forall x, f1 x ≡{B} f2 x).
  split.
  - move => ? ?. reflexivity.
  - move => x y ? z. now symmetry.
  - move => x y z ? ? a. now transitivity (y a).
Defined.

Instance nat_equiv : equiv_on nat := {| equiv_rel := eq |}.
Instance bool_equiv : equiv_on bool := {| equiv_rel := eq |}.
Instance Prop_equiv : equiv_on Prop := {| equiv_rel := iff |}.

Definition surjection_wrt {A} {B} (e : equiv_on B) (f : A -> B) :=
  forall b, exists a, f a ≡{B} b.

Instance equiv_ran {A B} : equiv_on (A -> option B) | 100.
Proof.
  exists (fun f1 f2 => forall x, (exists n, f1 n = Some x) <-> (exists n, f2 n = Some x)).
  split; red.
  - reflexivity.
  - intros x y H1 z. now rewrite H1.
  - intros f1 f2 f3 H1 H2 x.
    now rewrite H1 H2.
Defined.

Notation "f ≡{ran} g" := (@equiv_rel _  equiv_ran f g) (at level 80).


text:
Require Export Induction.
Module NatList.

  Inductive natprod : Type :=
  | pair : nat -> nat -> natprod.

  Check (pair 3 5).

  Definition fst (p : natprod) : nat :=
    match p with
    | pair x y => x
    end.

  Definition snd (p : natprod) : nat :=
    match p with
    | pair x y => y
    end.

  Compute (fst (pair 3 5)).

  Notation "( x , y )" := (pair x y).

  Compute (fst (3,5)).

  Definition fst' (p : natprod) : nat :=
    match p with
    | (x,y) => x
    end.

  Definition snd' (p : natprod) : nat :=
    match p with
    | (x,y) => y
    end.

  Definition swap_pair (p : natprod) : natprod :=
    match p with
    | (x,y) => (y,x)
    end.

  Theorem surjective_pairing' : forall (n m : nat),
      (n,m) = (fst (n,m), snd (n,m)).
  Proof.
    reflexivity. Qed.

  Theorem surjective_pairing : forall (p : natprod),
      p = (fst p, snd p).
  Proof.
    intros p.
    destruct p as [n m].
    simpl. reflexivity. Qed.

  Theorem snd_fst_is_swap : forall (p : natprod),
      (snd p, fst p) = swap_pair p.
  Proof.
    intros p.
    destruct p as [n m].
    simpl.
    reflexivity.
  Qed.

  Theorem fst_swap_is_snd : forall (p : natprod),
      fst (swap_pair p) = snd p.
  Proof.
    intros p.
    destruct p as [n m].
    simpl.
    reflexivity.
  Qed.

  Inductive natlist : Type :=
  | nil : natlist
  | cons : nat -> natlist -> natlist.

  Definition mylist := cons 1 (cons 2 (cons 3 nil)).

  Notation "x :: l" := (cons x l)
                         (at level 60, right associativity).
  Notation "[ ]" := nil.
  Notation "[ x ; .. ; y ]" := (cons x .. (cons y nil) ..).

  Definition mylist1 := 1 :: (2 :: (3 :: nil)).
  Definition mylist2 := 1 :: 2 :: 3 :: nil.
  Definition mylist3 := [1;2;3].

  Notation "x + y" := (plus x y)
                        (at level 50, left associativity).

  Fixpoint repeat (n count : nat) : natlist :=
    match count with
    | O => nil
    | S count' => n :: (repeat n count')
    end.

  Fixpoint length (l : natlist) : nat :=
    match l with
    | nil => O
    | h :: t => S (length t)
    end.

  Fixpoint app (l1 l2 : natlist) : natlist :=
    match l1 with
    | nil => l2
    | h :: t => h :: (app t l2)
    end.

  Notation "x ++ y" := (app x y)
                         (right associativity, at level 60).

  Example test_app1 : [1;2;3] ++ [4;5] = [1;2;3;4;5].
  Proof. reflexivity. Qed.
  Example test_app2: nil ++ [4;5] = [4;5].
  Proof. reflexivity. Qed.
  Example test_app3: [1;2;3] ++ nil = [1;2;3].
  Proof. reflexivity. Qed.

  Definition hd (default : nat) (l : natlist) : nat :=
    match l with
    | nil => default
    | h :: t => h
    end.

  Definition tl (l : natlist) : natlist :=
    match l with
    | nil => nil
    | h :: t => t
    end.

  Example test_hd1: hd 0 [1;2;3] = 1.
  Proof. reflexivity. Qed.
  Example test_hd2: hd 0 [] = 0.
  Proof. reflexivity. Qed.
  Example test_tl: tl [1;2;3] = [2;3].
  Proof. reflexivity. Qed.

  Fixpoint nonzeros (l : natlist) : natlist :=
    match l with
    | nil => nil
    | O :: t => nonzeros t
    | h :: t => h :: (nonzeros t)
    end.

  Example test_nonzeros:
    nonzeros [0;1;0;2;3;0;0] = [1;2;3].
  Proof. reflexivity. Qed.

  Fixpoint oddmembers (l : natlist) : natlist :=
    match l with
    | nil => nil
    | h :: t =>
      match oddb h with
      | false => oddmembers t
      | true => h :: (oddmembers t)
      end
    end.

  Example test_oddmembers:
    oddmembers [0;1;0;2;3;0;0] = [1;3].
  Proof. reflexivity. Qed.

  Definition countoddmembers (l : natlist) : nat :=
    length (oddmembers l).

  Example test_countoddmembers1:
    countoddmembers [1;0;3;1;4;5] = 4.
  Proof. reflexivity. Qed.

  Example test_countoddmembers2:
    countoddmembers [0;2;4] = 0.
  Proof. reflexivity. Qed.

  Example test_countoddmembers3:
    countoddmembers nil = 0.
  Proof. reflexivity. Qed.

  Inductive natlistprod : Type :=
  | lpair : natlist -> natlist -> natlistprod.

  Fixpoint alternate (l1 l2 : natlist) : natlist :=
    let lists := lpair l1 l2 in
    match lists with
    | lpair nil nil => nil
    | lpair nil l => l
    | lpair l nil => l
    | lpair (h1 :: t1) (h2 :: t2) => h1 :: h2 :: (alternate t1 t2)
    end.

  Example test_alternate1:
    alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
  Proof. reflexivity. Qed.

  Example test_alternate2:
    alternate [1] [4;5;6] = [1;4;5;6].
  Proof. reflexivity. Qed.

  Example test_alternate3:
    alternate [1;2;3] [4] = [1;4;2;3].
  Proof. reflexivity. Qed.

  Example test_alternate4:
    alternate [] [20;30] = [20;30].
  Proof. reflexivity. Qed.

  Definition bag := natlist.

  Fixpoint count (v : nat) (s : bag) : nat :=
    match s with
    | nil => 0
    | h :: t =>
      match beq_nat h v with
      | true => 1 + (count v t)
      | false => count v t
      end
    end.

  Example test_count1: count 1 [1;2;3;1;4;1] = 3.
  Proof. reflexivity. Qed.

  Example test_count2: count 6 [1;2;3;1;4;1] = 0.
  Proof. reflexivity. Qed.

  Definition sum : bag -> bag -> bag := app.

  Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.
  Proof. reflexivity. Qed.

  Definition add (v : nat) (s : bag) : bag := v :: s.

  Example test_add1: count 1 (add 1 [1;4;1]) = 3.
  Proof. reflexivity. Qed.

  Example test_add2: count 5 (add 1 [1;4;1]) = 0.
  Proof. reflexivity. Qed.

  Definition member (v:nat) (s:bag) : bool :=
    negb (beq_nat (count v s) 0).

  Example test_member1: member 1 [1;4;1] = true.
  Proof. reflexivity. Qed.

  Example test_member2: member 2 [1;4;1] = false.
  Proof. reflexivity. Qed.

author: noahdiewald

repo: softwarefoundations


text:
From Coq Require Import Arith ZArith Psatz Bool String List Program.Equality.
From CDF Require Import Sequences IMP Simulation.

Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope list_scope.

(** * 2. Compilation de IMP vers une machine à pile *)

(** ** 2.1.  Le langage cible: une machine à pile *)

(** Notre compilateur traduit IMP en le langage d'une machine très simple
    qui manipule une pile de nombres avec des instructions qui dépilent
    leurs arguments et empilent leur résultat.
    Cette machine ressemble aux anciennes calculatrices HP et leur
    "notation polonaise inversée".  Elle est aussi proche d'un
    sous-ensemble de la JVM, la machine virtuelle Java.
*)

(** *** 2.1.1.  Le jeu d'instructions *)

(** Voici le jeu d'instructions de la machine: *)

Inductive instr : Type :=
  | Iconst (n: Z)           (**r empile l'entier [n] *)
  | Ivar (x: ident)         (**r empile la valeur courante de la variable [x] *)
  | Isetvar (x: ident)      (**r dépile un entier, affecte-le à la variable [x] *)
  | Iadd                    (**r dépile deux entiers, empile leur somme *)
  | Iopp                    (**r dépile un entier, empile son opposé *)
  | Ibranch (d: Z)          (**r saute [d] instructions vers l'avant ou l'arrière *)
  | Ibeq (d1: Z) (d0: Z)    (**r dépile deux entiers, saute [d1] instructions si égaux, [d0] si différents *)
  | Ible (d1: Z) (d0: Z)    (**r dépile deux entiers, saute [d1] instructions si [<=], [d0] si [>] *)
  | Ihalt.                  (**r arrête l'exécution *)

(** Un code machine est une liste d'instructions. *)

Definition code := list instr.

(** La longueur (nombre d'instructions) d'un code machine. *)

Definition codelen (c: code) : Z := Z.of_nat (List.length c).

(** *** 2.1.2.  Sémantique opérationnelle *)

(** La machine opère sur un code [C] (une liste fixée d'instructions)
    et trois composants qui varient pendant l'exécution:
- un pointeur de code [pc], indiquant une position dans [C]
- une pile d'évaluation, contenant des nombres entiers
- un état mémoire, associant à chaque variable sa valeur entière.
*)

Definition stack : Type := list Z.

Definition config : Type := (Z * stack * store)%type.

(** [instr_at C pc = Some i] si [i] est l'instruction à la position
    [pc] dans le code [C]. *)

Fixpoint instr_at (C: code) (pc: Z) : option instr :=
  match C with
  | nil => None
  | i :: C' => if pc =? 0 then Some i else instr_at C' (pc - 1)
  end.

(** La sémantique de la machine est définie en style opérationnel "à petits pas"
    par une relation de transition.  Chaque transition représente l'exécution
    d'une instruction, à savoir, l'instruction à la position [pc] du code [C].
    La relation de transition relie les configurations de la machine
    "avant" et "après" l'exécution de l'instruction.
    La relation est paramétrée par le code [C] pour le programme complet.
    Il y a un cas pour chaque type d'instruction, sauf [Ihalt], qui
    ne fait pas de transition.
*)

Inductive transition (C: code): config -> config -> Prop :=
  | trans_const: forall pc σ s n,
      instr_at C pc = Some(Iconst n) ->
      transition C (pc    , σ     , s)
                   (pc + 1, n :: σ, s)
  | trans_var: forall pc σ s x,
      instr_at C pc = Some(Ivar x) ->
      transition C (pc    , σ       , s)
                   (pc + 1, s x :: σ, s)
  | trans_setvar: forall pc σ s x n,
      instr_at C pc = Some(Isetvar x) ->
      transition C (pc    , n :: σ, s)
                   (pc + 1, σ     , update x n s)
  | trans_add: forall pc σ s n1 n2,
      instr_at C pc = Some(Iadd) ->
      transition C (pc    , n2 :: n1 :: σ , s)
                   (pc + 1, (n1 + n2) :: σ, s)
  | trans_opp: forall pc σ s n,
      instr_at C pc = Some(Iopp) ->
      transition C (pc    , n :: σ    , s)
                   (pc + 1, (- n) :: σ, s)
  | trans_branch: forall pc σ s d pc',
      instr_at C pc = Some(Ibranch d) ->
      pc' = pc + 1 + d ->
      transition C (pc , σ, s)
                   (pc', σ, s)
  | trans_beq: forall pc σ s d1 d0 n1 n2 pc',
      instr_at C pc = Some(Ibeq d1 d0) ->
      pc' = pc + 1 + (if n1 =? n2 then d1 else d0) ->
      transition C (pc , n2 :: n1 :: σ, s)
                   (pc', σ            , s)
  | trans_ble: forall pc σ s d1 d0 n1 n2 pc',
      instr_at C pc = Some(Ible d1 d0) ->
      pc' = pc + 1 + (if n1 <=? n2 then d1 else d0) ->
      transition C (pc , n2 :: n1 :: σ, s)
                   (pc', σ            , s).

(** Comme nous l'avions fait dans le cas de la sémantique à réduction d'IMP,
    nous définissons l'exécution d'un code machine en termes de suites
    de transitions. *)

Definition transitions (C: code): config -> config -> Prop :=
  star (transition C).

(** L'exécution démarre avec [pc = 0] et une pile vide.
    Elle s'arrête avec succès quand [pc] pointe sur une instruction [Ihalt]
    et la pile est vide. *)

Definition machine_terminates (C: code) (s_init: store) (s_final: store) : Prop :=
  exists pc, transitions C (0, nil, s_init) (pc, nil, s_final)
          /\ instr_at C pc = Some Ihalt.

(** La machine peut aussi diverger ("boucler") en faisant une infinité
    de transitions. *)

Definition machine_diverges (C: code) (s_init: store) : Prop :=
  infseq (transition C) (0, nil, s_init).

(** Enfin, la machine peut se bloquer en erreur après un nombre fini
    de transitions. *)

Definition machine_goes_wrong (C: code) (s_init: store) : Prop :=
  exists pc σ s,
      transitions C (0, nil, s_init) (pc, σ, s)
   /\ irred (transition C) (pc, σ, s)
   /\ (instr_at C pc <> Some Ihalt \/ σ <> nil).

(** *** Exercice (2 étoiles). *)

(** Pour tester l'exécution d'un code machine, il est pratique de définir
    la sémantique de la machine comme une fonction exécutable et non
    plus seulement par une relation.  Nous avons déjà vu cette approche
    dans le cadre du langage IMP avec la fonction [cexec_f].

    Afin de garantir la terminaison de la fonction d'exécution,
    il faut borner a priori le nombre d'instruction exécutées
    à l'aide d'un paramètre [fuel] de type [nat].  Dès lors, il y a
    trois résultats possibles pour une exécution:
*)

Inductive machine_result : Type :=
  | OK (s: store)    (**r la machine s'arrête sur l'état final donné *)
  | Stuck            (**r la machine rencontre une erreur *)
  | Timeout.         (**r la machine n'a plus de fuel *)

(** Compléter les cas manquants dans la définition ci-dessous. *)

Fixpoint mach_exec (C: code) (fuel: nat)
                   (pc: Z) (σ: stack) (s: store) : machine_result :=
  match fuel with
  | O => Timeout
  | S fuel' =>
      match instr_at C pc, σ with
      | Some Ihalt, nil => OK s
      | Some (Iconst n), σ => mach_exec C fuel' (pc + 1) (n :: σ) s
      (* FILL IN HERE *)
      | _, _ => Stuck
      end
  end.

(** ** 2.2. Le schéma de compilation *)

(** Nous allons maintenant définir la compilation des expressions et des
    commandes IMP vers des morceaux de code machine. *)

(** Le code produit pour une expression arithmétique [a] s'exécute
    en séquence (sans faire de branchements) et laisse la valeur de [a]
    au sommet de la pile.

    C'est la traduction bien connue de la notation algébrique vers
    la notation polonaise inverse.  La seule subtilité est que la machine
    n'a pas d'instruction de soustraction, et donc, pour calculer [a - b],
    il faut ajouter [a] et l'opposé de [b].
*)

Fixpoint compile_aexp (a: aexp) : code :=
  match a with
  | CONST n => Iconst n :: nil
  | VAR x => Ivar x :: nil
  | PLUS a1 a2  => compile_aexp a1 ++ compile_aexp a2 ++ Iadd :: nil
  | MINUS a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Iopp :: Iadd :: nil
  end.

(** Exemples de code compilé *)

Eval compute in (compile_aexp (PLUS (CONST 1) (CONST 2))).

(** Résultat: [Iconst 1 :: Iconst 2 :: Iadd :: nil] *)

Eval compute in (compile_aexp (PLUS (VAR "x") (MINUS (VAR "y") (CONST 1)))).

(** Résultat: [Ivar "x" :: Ivar "y" :: Iconst 1 :: Iopp :: Iadd :: Iadd :: nil]. *)

(** Pour une expressions booléenne [b], notre premier réflexe serait
    de produire du code machine qui laisse [1] ou [0] au sommet de la
    pile, suivant que [b] est vraie ou fausse.  Le code produit pour
    les commandes [IFTHENELSE] et [WHILE] effectuerait alors un saut
    [Ibeq] conditionnel sur cette valeur 0/1 de [b].

    Cependant, il est plus simple et plus efficace de traduire l'expression
    booléenne [b] par un code machine qui saute [d1] ou [d0] instructions
    en avant, suivant que [b] est vraie ou fausse.  La valeur 0/1 de [b]
    n'est jamais calculée explicitement, et la pile est inchangée.
*)

Fixpoint compile_bexp (b: bexp) (d1: Z) (d0: Z) : code :=
  match b with
  | TRUE => if d1 =? 0 then nil else Ibranch d1 :: nil
  | FALSE => if d0 =? 0 then nil else Ibranch d0 :: nil
  | EQUAL a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Ibeq d1 d0 :: nil
  | LESSEQUAL a1 a2 => compile_aexp a1 ++ compile_aexp a2 ++ Ible d1 d0 :: nil
  | NOT b1 => compile_bexp b1 d0 d1
  | AND b1 b2 =>
      let code2 := compile_bexp b2 d1 d0 in
      let code1 := compile_bexp b1 0 (codelen code2 + d0) in
      code1 ++ code2
  end.

(** Se reporter aux transparents du cours pour une explication du
    mystérieux déplacement [codelen code2 + d0] dans le cas [AND]. *)

(** Vite des exemples. *)

Eval compute in (compile_bexp (EQUAL (VAR "x") (CONST 1)) 12 34).

(** Résultat: [ Ivar "x" :: Iconst 1 :: Ibeq 12 34 :: nil ]. *)

Eval compute in (compile_bexp (AND (LESSEQUAL (CONST 1) (VAR "x"))
                                   (LESSEQUAL (VAR "x") (CONST 10))) 0 10).

(** Résultat: [ Iconst 1 :: Ivar "x" :: Ible 0 13 ::
                Ivar "x" :: Iconst 10 :: Ible 0 10 :: nil ] *)

Eval compute in (compile_bexp (OR (LESSEQUAL (CONST 1) (VAR "x"))
                                  (LESSEQUAL (VAR "x") (CONST 10))) 0 10).

(** Résultat: [ Iconst 1 :: Ivar "x" :: Ible 3 0 ::
                Ivar "x" :: Iconst 10 :: Ible 0 10 :: nil ] *)

Eval compute in (compile_bexp (NOT (AND TRUE FALSE)) 12 34).

(** Résultat: [ Ibranch 12 :: nil ] *)

(** Pour finir, voici la compilation des commandes.
    Le code produit pour la commande [c] met à jour l'état mémoire
    (les valeurs des variables) comme prescrit par la sémantique de [c].
    Il ne change pas la pile.

    Là encore, on se reportera aux transparents du cours pour une
    explication des déplacements sur les instructions de branchement.
*)

Fixpoint compile_com (c: com) : code :=
  match c with
  | SKIP =>
      nil
  | ASSIGN x a =>
      compile_aexp a ++ Isetvar x :: nil
  | SEQ c1 c2 =>
      compile_com c1 ++ compile_com c2
  | IFTHENELSE b ifso ifnot =>
      let code_ifso := compile_com ifso in
      let code_ifnot := compile_com ifnot in
      compile_bexp b 0 (codelen code_ifso + 1)
      ++ code_ifso
      ++ Ibranch (codelen code_ifnot)
      :: code_ifnot
  | WHILE b body =>
      let code_body := compile_com body in
      let code_test := compile_bexp b 0 (codelen code_body + 1) in
      code_test
      ++ code_body
      ++ Ibranch (- (codelen code_test + codelen code_body + 1)) :: nil
  end.

(** Le code compilé pour un programme complet [p] (une commande)
    est similaire, mais termine proprement sur une instruction [Ihalt]. *)

Definition compile_program (p: com) : code :=
  compile_com p ++ Ihalt :: nil.

(** Exemples de compilation: *)

Eval compute in (compile_program (ASSIGN "x" (PLUS (VAR "x") (CONST 1)))).

(** Résultat: [ Ivar "x" :: Iconst 1 :: Iadd :: Isetvar "x" :: Ihalt :: nil ] *)

Eval compute in (compile_program (WHILE TRUE SKIP)).

(** Résultat: [ Ibranch (-1) :: Ihalt :: nil ]. *)

Eval compute in (compile_program (IFTHENELSE (EQUAL (VAR "x") (CONST 1)) (ASSIGN "x" (CONST 0)) SKIP)).

(** Résultat: [ Ivar "x" :: Iconst 1 :: Ibeq 0 3 ::
                 Iconst 0 :: Isetvar "x" :: Ibranch 0 :: Ihalt :: nil ]. *)

(** *** Exercice (1 étoile) *)

(** Le dernier exemple ci-dessus montre une inefficacité mineure dans le code
    engendré pour [IFTHENELSE b c SKIP], à savoir l'instruction [Ibranch 0].
    Pouvez-vous modifier [compile_com] pour éviter cette inefficacité?
    Indication: la fonction ci-dessous vous sera utile. *)

Definition smart_Ibranch (d: Z) : code :=
  if d =? 0 then nil else Ibranch d :: nil.

(** ** 2.3.  Correction du code produit pour les expressions *)

(** Pour raisonner sur les étapes d'exécution du code compilé, il faut
    considérer des morceaux de code machine [C2] qui sont à la position [pc]
    dans le code produit pour le programme tout entier, [C = C1 ++ C2 ++ C3].
    Le prédicat [code_at C pc C2] ci-dessous décrit exactement cette situation. *)

Inductive code_at: code -> Z -> code -> Prop :=
  | code_at_intro: forall C1 C2 C3 pc,
      pc = codelen C1 ->
      code_at (C1 ++ C2 ++ C3) pc C2.

(** Voici des lemmes utiles concernant les prédicats [instr_at] et [code_at]. *)

Lemma codelen_cons:
  forall i c, codelen (i :: c) = codelen c + 1.
Proof.
  unfold codelen; intros; cbn; lia.
Qed.

Lemma codelen_app:
  forall c1 c2, codelen (c1 ++ c2) = codelen c1 + codelen c2.
Proof.
  induction c1; intros.
- auto.
- cbn [app]. rewrite ! codelen_cons. rewrite IHc1. lia.
Qed.

Lemma instr_at_app:
  forall i c2 c1 pc,
  pc = codelen c1 ->
  instr_at (c1 ++ i :: c2) pc = Some i.
Proof.
  induction c1; simpl; intros; subst pc.
- auto.
- assert (A: codelen (a :: c1) =? 0 = false).
  { apply Z.eqb_neq. unfold codelen. cbn [length]. lia. }
  rewrite A. rewrite codelen_cons. apply IHc1. lia.
Qed.

Lemma code_at_head:
  forall C pc i C',
  code_at C pc (i :: C') ->
  instr_at C pc = Some i.
Proof.
  intros. inversion H. simpl. apply instr_at_app. auto.
Qed.

Lemma code_at_tail:
  forall C pc i C',
  code_at C pc (i :: C') ->
  code_at C (pc + 1) C'.
Proof.
  intros. inversion H.
  change (C1 ++ (i :: C') ++ C3)
    with (C1 ++ (i :: nil) ++ C' ++ C3).
  rewrite <- app_ass. constructor. rewrite codelen_app. subst pc. auto.
Qed.

Lemma code_at_app_left:
  forall C pc C1 C2,
  code_at C pc (C1 ++ C2) ->
  code_at C pc C1.
Proof.
  intros. inversion H. rewrite app_ass. constructor. auto.
Qed.

Lemma code_at_app_right:
  forall C pc C1 C2,
  code_at C pc (C1 ++ C2) ->
  code_at C (pc + codelen C1) C2.
Proof.
  intros. inversion H. rewrite app_ass. rewrite <- app_ass.
  constructor. rewrite codelen_app. subst pc. auto.
Qed.

Lemma code_at_app_right2:
  forall C pc C1 C2 C3,
  code_at C pc (C1 ++ C2 ++ C3) ->
  code_at C (pc + codelen C1) C2.
Proof.
  intros. apply code_at_app_right. apply code_at_app_left with (C2 := C3).
  rewrite app_ass; auto.
Qed.

Lemma code_at_nil:
  forall C pc C1,
  code_at C pc C1 -> code_at C pc nil.
Proof.
  intros. inversion H. subst. change (C1 ++ C3) with (nil ++ C1 ++ C3).
  constructor. auto.
Qed.

Lemma instr_at_code_at_nil:
  forall C pc i, instr_at C pc = Some i -> code_at C pc nil.
Proof.
  induction C; cbn; intros.
- discriminate.
- destruct (pc =? 0) eqn:PC.
+ assert (pc = 0) by (apply Z.eqb_eq; auto). subst pc.
  change (a :: C) with (nil ++ nil ++ (a :: C)). constructor. auto.
+ assert (A: code_at C (pc - 1) nil) by eauto.
  inversion A; subst.
  apply code_at_intro with (C1 := a :: C1) (C3 := C3).
  rewrite codelen_cons. lia.
Qed.

(** Nous mettons ces lemmes dans une "base d'indices" ("hint database")
    afin que Coq puisse les utiliser automatiquement. *)

Hint Resolve code_at_head code_at_tail code_at_app_left code_at_app_right
             code_at_app_right2 code_at_nil instr_at_code_at_nil: code.
Hint Rewrite codelen_app codelen_cons Z.add_assoc Z.add_0_r : code.

(** Rappelons le contrat que nous avons donné pour le code
    compilé pour une expression arithmétique [a].  Il est censé
  - s'exécuter en séquence (pas de branchements)
  - laisser la valeur de [a] au sommet de la pile
  - préserver l'état mémoire.

    Démontrons que le code [compile_aexp a] respecte ce contrat.
    La démonstration est une jolie récurrence sur la forme de [a]. *)

Lemma compile_aexp_correct:
  forall C s a pc σ,
  code_at C pc (compile_aexp a) ->
  transitions C
       (pc, σ, s)
       (pc + codelen (compile_aexp a), aeval a s :: σ, s).
Proof.
  induction a; simpl; intros.

- (* CONST *)
  apply star_one. apply trans_const. eauto with code.

- (* VAR *)
  apply star_one. apply trans_var. eauto with code.

- (* PLUS *)
  eapply star_trans. apply IHa1. eauto with code.
  eapply star_trans. apply IHa2. eauto with code.
  apply star_one. autorewrite with code. apply trans_add. eauto with code.

- (* MINUS *)
  eapply star_trans. apply IHa1. eauto with code.
  eapply star_trans. apply IHa2. eauto with code.
  eapply star_trans.
  apply star_one. apply trans_opp. eauto with code.
  apply star_one.
  replace (aeval a1 s - aeval a2 s)
     with (aeval a1 s + (- aeval a2 s))
       by lia.
  autorewrite with code. apply trans_add. eauto with code.
Qed.

(** La vérification de la compilation des expressions booléennes est similaire.
    On rappelle le contrat pour le code produit par [compile_bexp b d1 d0]:
  - il doit sauter [d1] instructions si [b] s'évalue à vrai,
    [d0] instruction si [b] s'évalue à faux;
  - il doit préserver la pile et l'état mémoire.
*)

Lemma compile_bexp_correct:
  forall C s b d1 d0 pc σ,
  code_at C pc (compile_bexp b d1 d0) ->
  transitions C
       (pc, σ, s)
       (pc + codelen (compile_bexp b d1 d0) + (if beval b s then d1 else d0), σ, s).
Proof.
  induction b; cbn; intros.

- (* TRUE *)
  destruct (d1 =? 0) eqn:Z.
  + (* déplacement = zéro: aucune instruction n'est produite *)
    assert (d1 = 0) by (apply Z.eqb_eq; auto). subst d1.
    autorewrite with code. apply star_refl.
  + (* un branchement est produit *)
    apply star_one. apply trans_branch with (d := d1). eauto with code. auto.

- (* FALSE *)
  destruct (d0 =? 0) eqn:Z.
  + (* déplacement = zéro: aucune instruction n'est produite *)
    assert (d0 = 0) by (apply Z.eqb_eq; auto). subst d0.
    autorewrite with code. apply star_refl.
  + (* un branchement est produit *)
    apply star_one. apply trans_branch with (d := d0). eauto with code. auto.

- (* EQUAL *)
  eapply star_trans. apply compile_aexp_correct with (a := a1). eauto with code.
  eapply star_trans. apply compile_aexp_correct with (a := a2). eauto with code.
  apply star_one. apply trans_beq with (d1 := d1) (d0 := d0). eauto with code.
  autorewrite with code. auto.

- (* LESSEQUAL *)
  eapply star_trans. apply compile_aexp_correct with (a := a1). eauto with code.
  eapply star_trans. apply compile_aexp_correct with (a := a2). eauto with code.
  apply star_one. apply trans_ble with (d1 := d1) (d0 := d0). eauto with code.
  autorewrite with code. auto.

- (* NOT *)
  replace (if negb (beval b s) then d1 else d0)
     with (if beval b s then d0 else d1).
  apply IHb. auto.
  destruct (beval b s); auto.

- (* AND *)
  set (code2 := compile_bexp b2 d1 d0) in *.
  set (code1 := compile_bexp b1 0 (codelen code2 + d0)) in *.
  eapply star_trans. apply IHb1. eauto with code.
  fold code1. destruct (beval b1 s); cbn.
  + (* b1 s'évalue en true, le code pour b2 est exécuté *)
    autorewrite with code. apply IHb2. eauto with code.
  + (* b1 s'évalue en false, le code pour b2 est sauté *)
    autorewrite with code. apply star_refl.
Qed.

(** ** 2.4.  Correction du code produit pour les commandes qui terminent *)

(** Supposons que la commande [c], démarrée dans l'état [s], termine dans
    l'état [s'].  Montrons alors que la machine, à partir du début du
    code [compile_com c] produit pour [c] et à partir de l'état [s],
    effectue un nombre fini de transitions et atteint la fin du code
    [compile_com c] et l'état [s'].

    Pour caractériser la terminaison de la commande [c], nous utilisons
    la sémantique naturelle d'IMP et son prédicat [exec s c s'].
    La démonstration se fait sans peine par récurrence sur la dérivation
    de cette exécution [exec s c s'].  Une récurrence sur la structure
    de [c] ne suffirait pas pour gérer le cas des boucles.
*)

Lemma compile_com_correct_terminating:
  forall s c s',
  cexec s c s' ->
  forall C pc σ,
  code_at C pc (compile_com c) ->
  transitions C
      (pc, σ, s)
      (pc + codelen (compile_com c), σ, s').
Proof.
  induction 1; cbn; intros.

- (* SKIP *)
  autorewrite with code. apply star_refl.

- (* ASSIGN *)
  eapply star_trans. apply compile_aexp_correct with (a := a). eauto with code.
  apply star_one. autorewrite with code. apply trans_setvar. eauto with code.

- (* SEQUENCE *)
  eapply star_trans.
  apply IHcexec1. eauto with code.
  autorewrite with code. apply IHcexec2. eauto with code.

- (* IFTHENELSE *)
  set (code1 := compile_com c1) in *.
  set (code2 := compile_com c2) in *.
  set (codeb := compile_bexp b 0 (codelen code1 + 1)) in *.
  eapply star_trans.
  apply compile_bexp_correct with (b := b). eauto with code.
  fold codeb. destruct (beval b s); autorewrite with code.
  + (* la branche "then" est exécutée *)
    eapply star_trans. apply IHcexec. eauto with code.
    fold code1. apply star_one. apply trans_branch with (d := codelen code2). eauto with code. lia.
  + (* la branche "else" est exécutée *)
    replace (pc + codelen codeb + codelen code1 + codelen code2 + 1)
       with (pc + codelen codeb + codelen code1 + 1 + codelen code2) by lia.
    apply IHcexec. eauto with code.

- (* WHILE stop *)
  set (code_body := compile_com c) in *.
  set (code_branch := compile_bexp b 0 (codelen code_body + 1)) in *.
  set (d := - (codelen code_branch + codelen code_body + 1)) in *.
  eapply star_trans. apply compile_bexp_correct with (b := b). eauto with code.
  rewrite H. fold code_branch. autorewrite with code. apply star_refl.

- (* WHILE loop *)
  set (code_body := compile_com c) in *.
  set (code_branch := compile_bexp b 0 (codelen code_body + 1)) in *.
  set (d := - (codelen code_branch + codelen code_body + 1)) in *.
  eapply star_trans. apply compile_bexp_correct with (b := b). eauto with code.
  rewrite H. fold code_branch. autorewrite with code.
  eapply star_trans. apply IHcexec1. eauto with code.
  eapply star_trans.
  apply star_one. apply trans_branch with (d := d). eauto with code. eauto.
  replace (pc + codelen code_branch + codelen code_body + 1 + d)
     with pc
       by lia.
  replace (pc + codelen code_branch + codelen code_body + 1)
     with (pc + codelen (compile_com (WHILE b c)))
       by (cbn; autorewrite with code; auto).
  apply IHcexec2. auto.
Qed.

(** En corollaire, nous obtenons la correction du code compilé pour un
    programme complet [p], dans le cas où il termine. *)

Theorem compile_program_correct_terminating:
  forall s c s',
  cexec s c s' ->
  machine_terminates (compile_program c) s s'.
Proof.
  intros.
  set (C := compile_program c).
  assert (CODEAT: code_at C 0 (compile_com c ++ Ihalt :: nil)).
  { replace C with (nil ++ compile_program c ++ nil).
    apply code_at_intro. auto.
    rewrite app_nil_r; auto. }
  unfold machine_terminates.
  exists (0 + codelen (compile_com c)); split.
- apply compile_com_correct_terminating. auto. eauto with code.
- eauto with code.
Qed.

(** *** Exercice (2 étoiles) *)

(** Dans un exercice précédent, vous avez modifié [compile_com] afin
    d'utiliser [smart_Ibranch] au lieu de [Ibranch] et de produire
    du code plus efficace.  Il vous reste à adapter la démonstration
    de [compile_com_correct_terminating] en conséquence.
    Indication: montrer d'abord le lemme ci-dessous. *)

Lemma transitions_smart_Ibranch:
  forall C pc d pc' σ s,
  code_at C pc (smart_Ibranch d) ->
  pc' = pc + codelen (smart_Ibranch d) + d ->
  transitions C (pc, σ, s) (pc', σ, s).
Proof.
  unfold smart_Ibranch; intros.
  (* À COMPLÉTER *)
Abort.

(** *** Exercice (4 étoiles). *)

(** Considérons une boucle avec un test d'arrêt simple, comme par exemple
    [WHILE (LESSEQUAL a1 a2) c].  Le code compilé exécute deux branchements
    par itération de la boucle: un branchement conditionnel [Ible] pour
    tester la condition d'arrêt, et un branchement inconditionnel [Ibranch]
    pour retourner au début de la boucle.  On peut se ramener à un
    seul branchement par itération en mettant le code pour [c] avant
    le code qui teste la condition [b]:
<<
     compile_com c ++ compile_bexp b delta1 0
>>
    avec [delta1] choisi de sorte à retourner au début du code [compile_com c]
    lorsque [b] est vraie.

    En soi, cette approche implémente une boucle de type do-while,
    où la première itération de la boucle est toujours exécutée.
    Pour une boucle de type while, à la première itération il faut
    sauter par-dessus le code de [c] et vers le code qui teste [b]:
<<
    Ibranch (codelen(compile_com c)) :: compile_com c ++ compile_bexp b delta1 0
>>
    Le but de cet exercice est de modifier [compile_com] pour implémenter
    cette compilation améliorée des boucles, puis de démontrer sa correction
    en ajustant l'énoncé et la démonstration de [compile_com_correct_terminating].
    La difficulté, et la raison pour les 4 étoiles, est que l'hypothèse
    [code_at C pc (compile_com c)] n'est plus vraie si [c] est une boucle
    et nous sommes à la deuxième itération de la boucle.  Il faut inventer
    une hypothèse plus faible, qui laisse plus de flexibilité dans
    la relation entre [c] et [pc]. *)

(** ** 2.5.  Correction du code produit pour les commandes, cas général *)

(** Nous allons maintenant renforcer le résultat de préservation sémantique
    de la section 2.4 afin qu'il ne soit plus restreint aux programmes IMP
    qui terminent, mais s'applique aussi aux programmes qui divergent.
    Pour ce faire, nous abandonnons la sémantique naturelle des commandes
    et passons à la sémantique par transitions et continuations.
    Ensuite, nous allons montrer un diagramme de simulation qui montre
    que chaque transition dans l'exécution du programme source est
    simulée (en un sens que nous allons définir) par zéro, une ou plusieurs
    transitions de la machine qui exécute le code compilé. *)

(** La première chose à faire est de relier les configurations [(c, k, s)]
    de la sémantique à continuations avec les configurations [(C, pc, σ, s)]
    de la machine.  Nous savons déjà comment relier une commande [c]
    et le code compilé qui lui correspond, à l'aide du prédicat [code_at].
    Il faut maintenant définir une relation entre une continuation [k]
    et le code compilé.

    Intuitivement, lorsque la machine a terminé l'exécution du code
    produit pour la commande [c], c'est-à-dire lorsqu'elle atteint
    le point de programme [pc + codelen(compile_com c)], la machine
    devrait ensuite exécuter des instructions qui effectuent les calculs
    en attente décrits par la continuation [k], pour enfin atteindre
    une instruction [Ihalt] qui arrête la machine.

    Le prédicat inductif [compile_cont C k pc] ci-dessous formalise cette
    intuition.  Il dit que, à partir du pointeur de code [pc],
    il y a dans [C] des instructions qui effectuent les calculs en attente
    décrits dans [k], puis atteignent une instruction [Ihalt].
*)

Inductive compile_cont (C: code): cont -> Z -> Prop :=
  | ccont_stop: forall pc,
      instr_at C pc = Some Ihalt ->
      compile_cont C Kstop pc
  | ccont_seq: forall c k pc pc',
      code_at C pc (compile_com c) ->
      pc' = pc + codelen (compile_com c) ->
      compile_cont C k pc' ->
      compile_cont C (Kseq c k) pc
  | ccont_while: forall b c k pc d pc' pc'',
      instr_at C pc = Some(Ibranch d) ->
      pc' = pc + 1 + d ->
      code_at C pc' (compile_com (WHILE b c)) ->
      pc'' = pc' + codelen (compile_com (WHILE b c)) ->
      compile_cont C k pc'' ->
      compile_cont C (Kwhile b c k) pc
  | ccont_branch: forall d k pc pc',
      instr_at C pc = Some(Ibranch d) ->
      pc' = pc + 1 + d ->
      compile_cont C k pc' ->
      compile_cont C k pc.

(** Dès lors, une configuration [(c,k,s)] de la sémantique à continuations
    d'IMP est reliée à une configuration [(C, pc, σ, s')] de la machine
    si les conditions suivantes sont vraies:
    - Les états mémoire sont identiques: [s' = s].
    - La pile de la machine est vide: [σ = nil].
    - Le code machine au point [pc] est le code compilé de [c]:
      [code_at C pc (compile_com c)].
    - Le code machine au point [pc + codelen (compile_com c)] implémente
      la continuation [k], au sens du prédicat [compile_cont] ci-dessus.
*)

Inductive match_config (C: code): com * cont * store -> config -> Prop :=
  | match_config_intro: forall c k st pc,
      code_at C pc (compile_com c) ->
      compile_cont C k (pc + codelen (compile_com c)) ->
      match_config C (c, k, st) (pc, nil, st).

(** Tout est prêt pour démontrer la propriété de simulation attendue.
    Puisque certaines transitions au niveau IMP correspondent à zéro
    transitions de la machine, il nous faut un diagramme de simulation
    de type "étoile" (cf. les transparents).
<<
                      match_config
     c / k / st  ----------------------- machconfig
       |                                   |
       |                                   | + ou ( * et |c',k'| < |c,k} )
       |                                   |
       v                                   v
    c' / k' / st' ----------------------- machconfig'
                      match_config
>>
    Remarquez la conclusion à droite du diagramme:
    - ou bien la machine effectue une ou plusieurs transitions,
    - ou bien la machine effectue zéro, une ou plusieurs transitions,
      mais la taille de la paire [c,k] décroît strictement.

    Il serait équivalent de montrer que:
    - ou bien la machine effectue une ou plusieurs transitions,
    - ou bien la machine effectue zéro transitions
      mais la taille de la paire [c,k] décroît strictement.

    Il se trouve que la première formulation, avec le cas "zéro une ou
    plusieurs" transitions, est plus facile à démontrer.
*)

(** Trouver la bonne mesure "anti-bégaiement" n'a rien d'évident.
    Après quelques tâtonnements, on tombe sur la mesure suivante.
    Elle est égale à la somme de la taille de la commande [c] en
    cours d'examen et des tailles des commandes apparaissant
    dans les noeuds [Kseq] de la continuation [k]. *)

Fixpoint com_size (c: com) : nat :=
  match c with
  | SKIP => 1%nat
  | ASSIGN x a => 1%nat
  | SEQ c1 c2 => (com_size c1 + com_size c2 + 1)%nat
  | IFTHENELSE b c1 c2 => (com_size c1 + com_size c2 + 1)%nat
  | WHILE b c1 => (com_size c1 + 1)%nat
  end.

Remark com_size_nonzero: forall c, (com_size c > 0)%nat.
Proof.
  induction c; cbn; lia.
Qed.

Fixpoint cont_size (k: cont) : nat :=
  match k with
  | Kstop => 0%nat
  | Kseq c k' => (com_size c + cont_size k')%nat
  | Kwhile b c k' => cont_size k'
  end.

Definition measure (impconf: com * cont * store) : nat :=
  match impconf with (c, k, m) => (com_size c + cont_size k)%nat end.

(** Nous aurons besoin de lemmes d'inversion sur le prédicat [compile_cont]. *)

Lemma compile_cont_Kstop_inv:
  forall C pc s,
  compile_cont C Kstop pc ->
  exists pc',
  star (transition C) (pc, nil, s) (pc', nil, s)
  /\ instr_at C pc' = Some Ihalt.
Proof.
  intros. dependent induction H.
- exists pc; split. apply star_refl. auto.
- destruct IHcompile_cont as (pc'' & A & B); auto.
  exists pc''; split; auto.
  eapply star_step; eauto. eapply trans_branch; eauto.
Qed.

Lemma compile_cont_Kseq_inv:
  forall C c k pc s,
  compile_cont C (Kseq c k) pc ->
  exists pc',
  star (transition C) (pc, nil, s) (pc', nil, s)
  /\ code_at C pc' (compile_com c)
  /\ compile_cont C k (pc' + codelen(compile_com c)).
Proof.
  intros. dependent induction H.
- exists pc; split. apply star_refl. split; congruence.
- edestruct IHcompile_cont as (pc'' & A & B). eauto.
  exists pc''; split; auto.
  eapply star_step; eauto. eapply trans_branch; eauto.
Qed.

Lemma compile_cont_Kwhile_inv:
  forall C b c k pc s,
  compile_cont C (Kwhile b c k) pc ->
  exists pc',
  plus (transition C) (pc, nil, s) (pc', nil, s)
  /\ code_at C pc' (compile_com (WHILE b c))
  /\ compile_cont C k (pc' + codelen(compile_com (WHILE b c))).
Proof.
  intros. dependent induction H.
- exists (pc + 1 + d); split.
  apply plus_one. eapply trans_branch; eauto.
  split; congruence.
- edestruct IHcompile_cont as (pc'' & A & B & D). eauto.
  exists pc''; split; auto.
  eapply plus_left. eapply trans_branch; eauto. apply plus_star; auto.
Qed.

Lemma match_config_skip:
  forall C k s pc,
  compile_cont C k pc ->
  match_config C (SKIP, k, s) (pc, nil, s).
Proof.
  intros. constructor.
- cbn. inversion H; eauto with code.
- cbn. autorewrite with code. auto.
Qed.

(** Voici enfin le diagramme de simulation et sa démonstration. *)

Lemma simulation_step:
  forall C impconf1 impconf2, step impconf1 impconf2 ->
  forall machconf1, match_config C impconf1 machconf1 ->
  exists machconf2,
      (plus (transition C) machconf1 machconf2
       \/ (star (transition C) machconf1 machconf2
           /\ (measure impconf2 < measure impconf1)%nat))
   /\ match_config C impconf2 machconf2.
Proof.
  destruct 1; intros machconf1 MATCH; inversion MATCH; clear MATCH; subst; cbn in *.

- (* assign *)
  econstructor; split.
+ left. eapply plus_right. eapply compile_aexp_correct; eauto with code.
  eapply trans_setvar; eauto with code.
+ autorewrite with code in *. apply match_config_skip. auto.

- (* seq *)
  econstructor; split.
+ right; split. apply star_refl. lia.
+ autorewrite with code in *. constructor. eauto with code.
  eapply ccont_seq; eauto with code.

- (* if *)
  set (code1 := compile_com c1) in *.
  set (codeb := compile_bexp b 0 (codelen code1 + 1)) in *.
  set (code2 := compile_com c2) in *.
  autorewrite with code in *.
  econstructor; split.
+ right; split.
  apply compile_bexp_correct with (b := b). eauto with code.
  destruct (beval b s); lia.
+ fold codeb. destruct (beval b s).
  * autorewrite with code. constructor. eauto with code.
    eapply ccont_branch. eauto with code. eauto.
    fold code1.
    replace (pc + codelen codeb + codelen code1 + 1 + codelen code2)
       with (pc + codelen codeb + codelen code1 + codelen code2 + 1) by lia.
    auto.
  * autorewrite with code. constructor. eauto with code. auto.
    fold code2.
    replace (pc + codelen codeb + codelen code1 + 1 + codelen code2)
       with (pc + codelen codeb + codelen code1 + codelen code2 + 1) by lia.
    auto.

- (* while stop *)
  set (codec := compile_com c) in *.
  set (codeb := compile_bexp b 0 (codelen codec + 1)) in *.
  econstructor; split.
+ right; split.
  apply compile_bexp_correct with (b := b). eauto with code.
  assert (com_size c > 0)%nat by apply com_size_nonzero. lia.
+ rewrite H. fold codeb. autorewrite with code in *.
  apply match_config_skip. auto.

- (* while loop *)
  set (codec := compile_com c) in *.
  set (codeb := compile_bexp b 0 (codelen codec + 1)) in *.
  econstructor; split.
+ right; split.
  apply compile_bexp_correct with (b := b). eauto with code.
  lia.
+ rewrite H. fold codeb. autorewrite with code in *.
  constructor. eauto with code.
  eapply ccont_while with (pc' := pc). eauto with code. fold codec. lia.
  auto.
  cbn. fold codec; fold codeb. eauto.
  autorewrite with code. auto.

- (* skip seq *)
  autorewrite with code in *.
  edestruct compile_cont_Kseq_inv as (pc' & X & Y & Z). eauto.
  econstructor; split.
+ right; split. eauto. lia.
+ constructor; auto.

- (* skip while *)
  autorewrite with code in *.
  edestruct compile_cont_Kwhile_inv as (pc' & X & Y & Z). eauto.
  econstructor; split.
+ left. eauto.
+ constructor; auto.
Qed.

(** Le plus dur est fait!  De jolies conséquences vont suivre, à l'aide des
    théorèmes généraux sur les simulations fournis par le module [Simulation].

    Tout d'abord, nous obtenons une autre démonstration que les programmes
    qui terminent sont correctement compilés, utilisant la sémantique
    à continuations au lieu de la sémantique naturelle pour caractériser
    les programmes IMP qui terminent. *)

Lemma match_initial_configs:
  forall c s,
  match_config (compile_program c) (c, Kstop, s) (0, nil, s).
Proof.
  intros. set (C := compile_program c).
  assert (code_at C 0 (compile_com c ++ Ihalt :: nil)).
  { replace C with (nil ++ (compile_com c ++ Ihalt :: nil) ++ nil).
    constructor; auto.
    rewrite app_nil_r; auto. }
  constructor.
- eauto with code.
- apply ccont_stop. eauto with code.
Qed.

Theorem compile_program_correct_terminating_2:
  forall c s s',
  star step (c, Kstop, s) (SKIP, Kstop, s') ->
  machine_terminates (compile_program c) s s'.
Proof.
  intros. set (C := compile_program c).
  edestruct (simulation_star _ _ _ _ _ _ (simulation_step C)) as (ms & A & B).
  eauto. apply match_initial_configs.
  inversion B; subst.
  edestruct compile_cont_Kstop_inv as (pc' & D & E). eauto.
  exists pc'; split; auto.
  eapply star_trans. eauto. cbn in D; autorewrite with code in D. eauto.
Qed.

(** Ensuite, et c'est plus nouveau, nous obtenons la preuve que les programmes
    qui divergent sont correctement compilés aussi: si le programme source
    fait une infinité de transitions dans la sémantique d'IMP, la machine
    exécutant le code compilé fait une infinité de transitions aussi. *)

Theorem compile_program_correct_diverging:
  forall c s,
  infseq step (c, Kstop, s) ->
  machine_diverges (compile_program c) s.
Proof.
  intros. set (C := compile_program c).
  eapply (simulation_infseq _ _ _ _ _ _ (simulation_step C)).
  eauto. apply match_initial_configs.
Qed.

author: xavierleroy

repo: cdf-sem-meca