From CoTypes Require Export coGlobal coLocal coProj.
From mathcomp Require Import all_ssreflect.
Require Import Paco.paco.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(*Example 5*)
Section Example5.
Variables (a b c d: ptcp) (k k' : ch) (u : value).
Hypotheses (Hac : a <> c) (Had : a <> d).
Definition g := GRec (GMsg (Action a b k) u (GRec (GBranch (Action c d k') ((GVar 1) :: (GMsg (Action a b k) u (GVar 0))::nil)))).
Definition l := ERec (EMsg Sd k u (EVar 0)).
Definition gc_aux gc := GCMsg (Action a b k) u (GCBranch (Action c d k') (cocons gc (cocons gc conil ))).
Definition gc_aux2 gc := GCMsg (Action a b k) u (GCBranch (Action c d k') ((to_coseq (gc :: gc ::nil)))).
CoFixpoint gc := gc_aux gc. (*Coq allows definition with gc_aux, obviously productive, we need to use gc_aux2 because unravel judgment has branching rule expecting a list of shap (to_coseq (...)*)

Lemma gc_aux_aux2 : gc_aux = gc_aux2.
Proof. fext. intros. rewrite /gc_aux /gc_aux2.
rewrite !utils.coeq. done.
Qed.

Lemma gc_eq : gc = gc_aux gc.
Proof. rewrite /gc. rewrite {1}(gc_match (cofix gc := _)).
rewrite {1}/gc_aux.
rewrite {3}/gc_aux.  done.
Qed.

Definition lc_aux lc := ECMsg Sd k u lc.
CoFixpoint lc := lc_aux lc.
Lemma lc_eq : lc = lc_aux lc.
Proof. rewrite /lc. rewrite {1}(ec_match (cofix ec := _ )).
rewrite {1}/lc_aux.
rewrite {2}/lc_aux. done.
Qed.
Print gUnravel. Print gUnravel2.
Lemma gUnravel_iff_R : forall e ec R, paco2 gUnravel_gen R e ec <->  paco2 (UnfgUnravel \o gUnravel2_gen) R e ec.
Proof. intros. split.
move : e ec. pcofix CIH.
intros. punfold H0.  induction H0. pclearbot. pfold.
constructor. rewrite /full_unf /=.  constructor.
inv H. eauto. eauto. pfold. con. con. done.
elim : gs gcs H H0. case=>//=. intros.
destruct gcs;try done. inv H1. con.
inv H4;auto. ssa.
punfold IHgUnravel_gen. inv IHgUnravel_gen. pfold. con.
rewrite full_unf_subst. done.
pfold. con.  con.
intros.
move : e ec H.  pcofix CIH. intros. punfold H0. inv H0.
inv H. apply/gUnravel_unf6. rewrite -H1. pfold. constructor.
inv H2;auto.
apply/gUnravel_unf6. rewrite -H1. pfold. constructor. done.
induction H3;auto. con;eauto.  inv H3;eauto.
apply/gUnravel_unf6. rewrite -H2. pfold. constructor.
Qed.

Lemma unravel_g_gc : gUnravel g gc.
Proof.
pcofix CIH.
pfold. con. pfold_reverse.
apply/gUnravel_iff_R.
pcofix CIH.
rewrite /g gc_eq gc_aux_aux2 /gc_aux2.
pfold. con. cbn. con. left.
pfold. con. cbn. con. ssa.
con.
- simpl. right. apply/CIH.
- con;try done. right. apply/CIH0.
Qed.

Lemma unravel_l_lc : lUnravel l lc.
Proof.
rewrite /l lc_eq. pcofix CIH. pfold. con. simpl.
con. rewrite lc_eq. auto.
Qed.

Lemma Project_example : CProject gc a lc.
Proof.
pcofix CIH.
rewrite gc_eq gc_aux_aux2 lc_eq.
pfold. con. rewrite /comp_dir /= eqxx //=. left.
pfold. rewrite lc_eq. rewrite /lc_aux. econstructor.
rewrite /comp_dir /=. have : a == c = false. apply/eqP=>//=. move =>->.
have : a == d = false. apply/eqP=>//=. move=>->. done.
simpl. auto.
intros. simpl in H. destruct H;subst.
- ssa. rewrite gc_eq /gc_aux. con. rewrite /comp_dir /= eqxx //=.
  right. rewrite lc_eq in CIH. done.
- destruct H;try done. subst. ssa. rewrite gc_eq /gc_aux. con. rewrite /comp_dir /= eqxx //=.
  right. rewrite lc_eq in CIH. done.
Qed.

End Example5.

Section Example19.
Variables (a b c d: ptcp) (k k' : ch) (u : value).
Definition state0 := GRec (GMsg (Action a b k) u (GRec (GBranch (Action c d k') ((GVar 1) :: (GMsg (Action a b k) u (GVar 0))::nil)))).

Definition state1 := (GRec (GBranch (Action c d k') (state0 :: (GMsg (Action a b k) u (GVar 0)::nil)))).

Definition state2 := GMsg (Action a b k) u state1.

Lemma trans_01 : nth GEnd (nextg_unf state0) 0 = state1.
Proof. done. Qed.

Lemma trans_10 : nth GEnd (nextg_unf state1) 0 = state0.
Proof. done. Qed.

Lemma trans_12 : nth GEnd (nextg_unf state1) 1 = state2.
Proof. done. Qed.

Lemma trans_20 : nth GEnd (nextg_unf state2) 0 = state1.
Proof. done. Qed.
End Example19.

Section Example22.
Definition Unravels g := gUnravel g (gtocoind g).
Lemma decide_Unravels : forall g, Unravels g <-> next_rec nil has_treeP (fun _ => true) g.
Proof. intros. rewrite /Unravels.  rewrite next_recP //=. Qed.
End Example22.

Require Import Projection.projectDecide.
Section Example25.
Variables (a b c d: ptcp) (k k' : ch) (u u' : value).
Hypotheses (Hca : c <> a) (Hcb : c <> b).
Definition g0 := GMsg (Action a b k) u (GMsg (Action c d k) u' GEnd).
Definition l0 := EMsg Sd k u' EEnd.
Definition pair_state0 := (g0,l0).

Definition g1 := (GMsg (Action c d k) u' GEnd).
Definition pair_state1 := (g1,l0).

Definition pair_state2 := (GEnd,EEnd).

Lemma pair_trans_01 : nth (GEnd,EEnd) (nextge_unf c pair_state0) 0 = pair_state1.
Proof. cbn. rewrite /comp_dir /=.
have : c == a = false. apply/eqP=>//=. move=>->.
have : c == b = false. apply/eqP=>//=. move=>->. simpl. done.
Qed.

Lemma pair_trans_12 : nth (GEnd,EEnd) (nextge_unf c pair_state1) 0 = pair_state2.
Proof. cbn. rewrite /comp_dir /= eqxx //=. Qed.
End Example25.


From Undecidability.L Require Import L Tactics.LTactics LBool.
(*From Undecidability.L.Complexity Require Import Monotonic UpToC.*)

Class eqbClass X (eqb : X -> X -> bool): Type :=
  _eqb_spec : forall (x y:X), reflect (x=y) (eqb x y).

Hint Mode eqbClass + -: typeclass_instances. (* treat argument as input and force evar-freeness*)

Definition eqb X eqb `{H:eqbClass (X:=X) eqb} := eqb.

Arguments eqb {_ _ _}: simpl never.

Lemma eqb_spec {X} {f : X -> X -> bool} {_:eqbClass f}:
  forall (x y:X), reflect (x=y) (eqb x y).
Proof.
  intros. eapply _eqb_spec.
Qed.

Instance eqbBool_inst : eqbClass Bool.eqb.
Proof.
  intros ? ?. eapply iff_reflect. rewrite eqb_true_iff. reflexivity.
Qed.

Lemma dec_reflect_remove {P Y} (d:dec P) b (H:reflect P b) (y y' : Y):
  (if d then y else y') = (if b then y else y').
Proof.
  destruct H,d;easy.
Qed.

Lemma eqDec_remove {X Y eqb} {H:eqbClass (X:=X) eqb} x x' (d:dec (x=x')) (a b : Y):
  (if d then a else b) = (if eqb x x' then a else b).
Proof.
  apply dec_reflect_remove. eapply eqb_spec.
Qed.

Class eqbCompT X {R:encodable X} eqb {H:eqbClass (X:=X) eqb} :=
  { c__eqbComp :nat;
    eqbTime x y:= min x y* c__eqbComp;
    comp_eqb : computableTime' eqb (fun x _ =>(5,fun y _ => (eqbTime (size (enc x)) (size (enc y)),tt)))
  }.
Arguments eqbCompT _ {_ _ _}.
Arguments c__eqbComp _ {_ _ _ _}.

Hint Mode eqbCompT + - - -: typeclass_instances.

Existing Instance comp_eqb.

Instance eqbComp_bool : eqbCompT bool.
Proof.
  evar (c:nat). exists c. unfold Bool.eqb.
  unfold enc;cbn.
  extract.
  solverec.
  [c]:exact 3.
  all:unfold c;try lia.
Qed.

Lemma eqbTime_le_l X {R : encodable X} (eqb : X -> X -> bool) {H : eqbClass eqb}
      {H' : eqbCompT X} x n':
  eqbTime (X:=X) x n' <= x * c__eqbComp X.
Proof.
  unfold eqbTime. rewrite Nat.le_min_l. easy.
Qed.

Lemma eqbTime_le_r X (R : encodable X) (eqb : X -> X -> bool) (H : eqbClass eqb)
      (eqbCompT : eqbCompT X) x n':
  eqbTime (X:=X) n' x <= x * c__eqbComp X.
Proof.
  unfold eqbTime. rewrite Nat.le_min_r. easy.
Qed.

(*
Lemma eqbTime_upToC X {R:encodable X} eqb {H:eqbClass (X:=X) eqb} {_:eqbCompT X}:
  eqbTime (X:=X) <=c (fun (x y:nat) => min x y).
Proof.
  unfold eqbTime. hnf.
  exists (c__eqbComp X). unfold leHO;repeat intro; cbn;nia.
Qed.
*)


(** * Smallstep: Small-step Operational Semantics *)

Require Export Imp.
Require Import JRWTactics.
Require Import DmoonTactics.

(** The evaluators we have seen so far (e.g., the ones for
    [aexp]s, [bexp]s, and commands) have been formulated in a
    "big-step" style -- they specify how a given expression can be
    evaluated to its final value (or a command plus a store to a final
    store) "all in one big step."

    This style is simple and natural for many purposes -- indeed,
    Gilles Kahn, who popularized its use, called it _natural
    semantics_.  But there are some things it does not do well.  In
    particular, it does not give us a natural way of talking about
    _concurrent_ programming languages, where the "semantics" of a
    program -- i.e., the essence of how it behaves -- is not just
    which input states get mapped to which output states, but also
    includes the intermediate states that it passes through along the
    way, since these states can also be observed by concurrently
    executing code.

    Another shortcoming of the big-step style is more technical, but
    critical in some situations.  To see the issue, suppose we wanted
    to define a variant of Imp where variables could hold _either_
    numbers _or_ lists of numbers (see the [HoareList] chapter for
    details).  In the syntax of this extended language, it will be
    possible to write strange expressions like [2 + nil], and our
    semantics for arithmetic expressions will then need to say
    something about how such expressions behave.  One
    possibility (explored in the [HoareList] chapter) is to maintain
    the convention that every arithmetic expressions evaluates to some
    number by choosing some way of viewing a list as a number -- e.g.,
    by specifying that a list should be interpreted as [0] when it
    occurs in a context expecting a number.  But this is really a bit
    of a hack.

    A much more natural approach is simply to say that the behavior of
    an expression like [2+nil] is _undefined_ -- it doesn't evaluate
    to any result at all.  And we can easily do this: we just have to
    formulate [aeval] and [beval] as [Inductive] propositions rather
    than Fixpoints, so that we can make them partial functions instead
    of total ones.

    However, now we encounter a serious deficiency.  In this language,
    a command might _fail_ to map a given starting state to any ending
    state for two quite different reasons: either because the
    execution gets into an infinite loop or because, at some point,
    the program tries to do an operation that makes no sense, such as
    adding a number to a list, and none of the evaluation rules can be
    applied.

    These two outcomes -- nontermination vs. getting stuck in an
    erroneous configuration -- are quite different.  In particular, we
    want to allow the first (permitting the possibility of infinite
    loops is the price we pay for the convenience of programming with
    general looping constructs like [while]) but prevent the
    second (which is just wrong), for example by adding some form of
    _typechecking_ to the language.  Indeed, this will be a major
    topic for the rest of the course.  As a first step, we need a
    different way of presenting the semantics that allows us to
    distinguish nontermination from erroneous "stuck states."

    So, for lots of reasons, we'd like to have a finer-grained way of
    defining and reasoning about program behaviors.  This is the topic
    of the present chapter.  We replace the "big-step" [eval] relation
    with a "small-step" relation that specifies, for a given program,
    how the "atomic steps" of computation are performed. *)

(* ########################################################### *)
(** * A Toy Language *)

(** To save space in the discussion, let's go back to an
    incredibly simple language containing just constants and
    addition.  (We use single letters -- [C] and [P] -- for the
    constructor names, for brevity.)  At the end of the chapter, we'll
    see how to apply the same techniques to the full Imp language.  *)

Inductive tm : Type :=
  | C : nat -> tm         (* Constant *)
  | P : tm -> tm -> tm.   (* Plus *)

Tactic Notation "tm_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "C" | Case_aux c "P" ].

(** Here is a standard evaluator for this language, written in the
    same (big-step) style as we've been using up to this point. *)

Fixpoint evalF (t : tm) : nat :=
  match t with
  | C n => n
  | P a1 a2 => evalF a1 + evalF a2
  end.

(** Now, here is the same evaluator, written in exactly the same
    style, but formulated as an inductively defined relation.  Again,
    we use the notation [t || n] for "[t] evaluates to [n]." *)
(**
                               --------                                (E_Const)
                               C n || n

                               t1 || n1
                               t2 || n2
                        ----------------------                         (E_Plus)
                        P t1 t2 || n1 + n2
*)

Reserved Notation " t '||' n " (at level 50, left associativity).

Inductive eval : tm -> nat -> Prop :=
  | E_Const : forall n,
      C n || n
  | E_Plus : forall t1 t2 n1 n2,
      t1 || n1 ->
      t2 || n2 ->
      P t1 t2 || (n1 + n2)

  where " t '||' n " := (eval t n).

Tactic Notation "eval_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "E_Const" | Case_aux c "E_Plus" ].

Module SimpleArith1.

(** Now, here is a small-step version. *)
(**
                     -------------------------------        (ST_PlusConstConst)
                     P (C n1) (C n2) ==> C (n1 + n2)

                              t1 ==> t1'
                         --------------------                        (ST_Plus1)
                         P t1 t2 ==> P t1' t2

                              t2 ==> t2'
                      ---------------------------                    (ST_Plus2)
                      P (C n1) t2 ==> P (C n1) t2'
*)

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_PlusConstConst : forall n1 n2,
      P (C n1) (C n2) ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
      t1 ==> t1' ->
      P t1 t2 ==> P t1' t2
  | ST_Plus2 : forall n1 t2 t2',
      t2 ==> t2' ->
      P (C n1) t2 ==> P (C n1) t2'

  where " t '==>' t' " := (step t t').

Tactic Notation "step_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "ST_PlusConstConst"
  | Case_aux c "ST_Plus1" | Case_aux c "ST_Plus2" ].

(** Things to notice:

    - We are defining just a single reduction step, in which
      one [P] node is replaced by its value.

    - Each step finds the _leftmost_ [P] node that is ready to
      go (both of its operands are constants) and rewrites it in
      place.  The first rule tells how to rewrite this [P] node
      itself; the other two rules tell how to find it.

    - A term that is just a constant cannot take a step. *)

(** Let's pause and check a couple of examples of reasoning with
    the [step] relation... *)

(** If [t1] can take a step to [t1'], then [P t1 t2] steps
    to [P t1' t2]: *)

Example test_step_1 :
      P
        (P (C 0) (C 3))
        (P (C 2) (C 4))
      ==>
      P
        (C (0 + 3))
        (P (C 2) (C 4)).
Proof.
  apply ST_Plus1. apply ST_PlusConstConst.  Qed.

(** **** Exercise: 1 star (test_step_2) *)
(** Right-hand sides of sums can take a step only when the
    left-hand side is finished: if [t2] can take a step to [t2'],
    then [P (C n) t2] steps to [P (C n)
    t2']: *)

Example test_step_2 :
      P
        (C 0)
        (P
          (C 2)
          (P (C 0) (C 3)))
      ==>
      P
        (C 0)
        (P
          (C 2)
          (C (0 + 3))).
Proof.
  repeat apply ST_Plus2. apply ST_PlusConstConst.
Qed.
(** [] *)

(* ########################################################### *)
(** * Relations *)

(** We will be using several different step relations, so it is
    helpful to generalize a bit... *)

(** A (binary) _relation_ on a set [X] is a family of propositions
    parameterized by two elements of [X] -- i.e., a proposition about
    pairs of elements of [X].  *)

Definition relation (X: Type) := X->X->Prop.

(** Our main examples of such relations in this chapter will be
    the single-step and multi-step reduction relations on terms, [==>]
    and [==>*], but there are many other examples -- some that come to
    mind are the "equals," "less than," "less than or equal to," and
    "is the square of" relations on numbers, and the "prefix of"
    relation on lists and strings. *)

(** One simple property of the [==>] relation is that, like the
    evaluation relation for our language of Imp programs, it is
    _deterministic_.

    _Theorem_: For each [t], there is at most one [t'] such that [t]
    steps to [t'] ([t ==> t'] is provable).  Formally, this is the
    same as saying that [==>] is deterministic. *)

(** _Proof sketch_: We show that if [x] steps to both [y1] and [y2]
    then [y1] and [y2] are equal, by induction on a derivation of
    [step x y1].  There are several cases to consider, depending on
    the last rule used in this derivation and in the given derivation
    of [step x y2].

      - If both are [ST_PlusConstConst], the result is immediate.

      - The cases when both derivations end with [ST_Plus1] or
        [ST_Plus2] follow by the induction hypothesis.

      - It cannot happen that one is [ST_PlusConstConst] and the other
        is [ST_Plus1] or [ST_Plus2], since this would imply that [x] has
        the form [P t1 t2] where both [t1] and [t2] are
        constants (by [ST_PlusConstConst]) _and_ one of [t1] or [t2] has
        the form [P ...].

      - Similarly, it cannot happen that one is [ST_Plus1] and the other
        is [ST_Plus2], since this would imply that [x] has the form
        [P t1 t2] where [t1] has both the form [P t1 t2] and
        the form [C n]. [] *)

Definition deterministic {X: Type} (R: relation X) :=
  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.

Theorem step_deterministic:
  deterministic step.
Proof.
  unfold deterministic. intros x y1 y2 Hy1 Hy2.
  generalize dependent y2.
  step_cases (induction Hy1) Case; intros y2 Hy2.
    Case "ST_PlusConstConst". step_cases (inversion Hy2) SCase.
      SCase "ST_PlusConstConst". reflexivity.
      SCase "ST_Plus1". inversion H2.
      SCase "ST_Plus2". inversion H2.
    Case "ST_Plus1". step_cases (inversion Hy2) SCase.
      SCase "ST_PlusConstConst". rewrite <- H0 in Hy1. inversion Hy1.
      SCase "ST_Plus1".
        rewrite <- (IHHy1 t1'0).
        reflexivity. assumption.
      SCase "ST_Plus2". rewrite <- H in Hy1. inversion Hy1.
    Case "ST_Plus2". step_cases (inversion Hy2) SCase.
      SCase "ST_PlusConstConst". rewrite <- H1 in Hy1. inversion Hy1.
      SCase "ST_Plus1". inversion H2.
      SCase "ST_Plus2".
        rewrite <- (IHHy1 t2'0).
        reflexivity. assumption.  Qed.

End SimpleArith1.

(* ########################################################### *)
(** ** Values *)

(** Let's take a moment to slightly generalize the way we state the
    definition of single-step reduction.  *)

(** It is useful to think of the [==>] relation as defining an
    _abstract machine_:

      - At any moment, the _state_ of the machine is a term.

      - A _step_ of the machine is an atomic unit of computation --
        here, a single "add" operation.

      - The _halting states_ of the machine are ones where there is no
        more computation to be done.
*)
(**
    We can then execute a term [t] as follows:

      - Take [t] as the starting state of the machine.

      - Repeatedly use the [==>] relation to find a sequence of
        machine states, starting with [t], where each state steps to
        the next.

      - When no more reduction is possible, "read out" the final state
        of the machine as the result of execution. *)

(** Intuitively, it is clear that the final states of the
    machine are always terms of the form [C n] for some [n].
    We call such terms _values_. *)

Inductive value : tm -> Prop :=
  v_const : forall n, value (C n).

(** Having introduced the idea of values, we can use it in the
    definition of the [==>] relation to write [ST_Plus2] rule in a
    slightly more elegant way: *)

(**
                     -------------------------------        (ST_PlusConstConst)
                     P (C n1) (C n2) ==> C (n1 + n2)

                              t1 ==> t1'
                         --------------------                        (ST_Plus1)
                         P t1 t2 ==> P t1' t2

                               value v1
                              t2 ==> t2'
                         --------------------                        (ST_Plus2)
                         P v1 t2 ==> P v1 t2'
*)
(** Again, the variable names here carry important information:
    by convention, [v1] ranges only over values, while [t1] and [t2]
    range over arbitrary terms.  (Given this convention, the explicit
    [value] hypothesis is arguably redundant.  We'll keep it for now,
    to maintain a close correspondence between the informal and Coq
    versions of the rules, but later on we'll drop it in informal
    rules, for the sake of brevity.) *)

(**  Here are the formal rules: *)

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_PlusConstConst : forall n1 n2,
          P (C n1) (C n2)
      ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
        t1 ==> t1' ->
        P t1 t2 ==> P t1' t2
  | ST_Plus2 : forall v1 t2 t2',
        value v1 ->                     (* <----- n.b. *)
        t2 ==> t2' ->
        P v1 t2 ==> P v1 t2'

  where " t '==>' t' " := (step t t').

Tactic Notation "step_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "ST_PlusConstConst"
  | Case_aux c "ST_Plus1" | Case_aux c "ST_Plus2" ].

(** **** Exercise: 3 stars (redo_determinism) *)
(** As a sanity check on this change, let's re-verify determinism

    Proof sketch: We must show that if [x] steps to both [y1] and [y2]
    then [y1] and [y2] are equal.  Consider the final rules used in
    the derivations of [step x y1] and [step x y2].

    - If both are [ST_PlusConstConst], the result is immediate.

    - It cannot happen that one is [ST_PlusConstConst] and the other
      is [ST_Plus1] or [ST_Plus2], since this would imply that [x] has
      the form [P t1 t2] where both [t1] and [t2] are
      constants (by [ST_PlusConstConst]) AND one of [t1] or [t2] has
      the form [P ...].

    - Similarly, it cannot happen that one is [ST_Plus1] and the other
      is [ST_Plus2], since this would imply that [x] has the form
      [P t1 t2] where [t1] both has the form [P t1 t2] and
      is a value (hence has the form [C n]).

    - The cases when both derivations end with [ST_Plus1] or
      [ST_Plus2] follow by the induction hypothesis. [] *)

(** Most of this proof is the same as the one above.  But to get
    maximum benefit from the exercise you should try to write it from
    scratch and just use the earlier one if you get stuck. *)

Ltac find_step_invc :=
  match goal with
    | [ H : step ?t ?t' |- _ ] => inversion H; subst; clear H
  end.

Ltac find_value_invc :=
  match goal with
    | [ H : value ?v |- _ ] => inversion H; subst; clear H
  end.

Theorem step_deterministic :
  deterministic step.
Proof.
  unfold deterministic. intros.
  generalize dependent y2.
  induction H; intros.
  - repeat find_step_invc.
    reflexivity.
  - find_step_invc.
    + find_step_invc.
    + erewrite IHstep; eauto.
    + find_value_invc.
      find_step_invc.
  - find_value_invc.
    find_step_invc; try solve [find_step_invc].
    erewrite IHstep; eauto.
Qed.

(** [] *)

(* ########################################################### *)
(** ** Strong Progress and Normal Forms *)

(** The definition of single-step reduction for our toy language is
    fairly simple, but for a larger language it would be pretty easy
    to forget one of the rules and create a situation where some term
    cannot take a step even though it has not been completely reduced
    to a value.  The following theorem shows that we did not, in fact,
    make such a mistake here. *)

(** _Theorem_ (_Strong Progress_): If [t] is a term, then either [t]
    is a value, or there exists a term [t'] such that [t ==> t']. *)

(** _Proof_: By induction on [t].

    - Suppose [t = C n]. Then [t] is a [value].

    - Suppose [t = P t1 t2], where (by the IH) [t1] is either a
      value or can step to some [t1'], and where [t2] is either a
      value or can step to some [t2']. We must show [P t1 t2] is
      either a value or steps to some [t'].

      - If [t1] and [t2] are both values, then [t] can take a step, by
        [ST_PlusConstConst].

      - If [t1] is a value and [t2] can take a step, then so can [t],
        by [ST_Plus2].

      - If [t1] can take a step, then so can [t], by [ST_Plus1].  [] *)

Theorem strong_progress : forall t,
  value t \/ (exists t', t ==> t').
Proof.
  tm_cases (induction t) Case.
    Case "C". left. apply v_const.
    Case "P". right. inversion IHt1.
      SCase "l". inversion IHt2.
        SSCase "l". inversion H. inversion H0.
          exists (C (n + n0)).
          apply ST_PlusConstConst.
        SSCase "r". inversion H0 as [t' H1].
          exists (P t1 t').
          apply ST_Plus2. apply H. apply H1.
      SCase "r". inversion H as [t' H0].
          exists (P t' t2).
          apply ST_Plus1. apply H0.  Qed.

(** This important property is called _strong progress_, because
    every term either is a value or can "make progress" by stepping to
    some other term.  (The qualifier "strong" distinguishes it from a
    more refined version that we'll see in later chapters, called
    simply "progress.") *)

(** The idea of "making progress" can be extended to tell us something
    interesting about [value]s: in this language [value]s are exactly
    the terms that _cannot_ make progress in this sense.

    To state this observation formally, let's begin by giving a name
    to terms that cannot make progress.  We'll call them _normal
    forms_. *)

Definition normal_form {X:Type} (R:relation X) (t:X) : Prop :=
  ~ exists t', R t t'.

(** This definition actually specifies what it is to be a normal form
    for an _arbitrary_ relation [R] over an arbitrary set [X], not
    just for the particular single-step reduction relation over terms
    that we are interested in at the moment.  We'll re-use the same
    terminology for talking about other relations later in the
    course. *)

(** We can use this terminology to generalize the observation we made
    in the strong progress theorem: in this language, normal forms and
    values are actually the same thing. *)

Lemma value_is_nf : forall v,
  value v -> normal_form step v.
Proof.
  unfold normal_form. intros v H. inversion H.
  intros contra. inversion contra. inversion H1.
Qed.

Lemma nf_is_value : forall t,
  normal_form step t -> value t.
Proof. (* a corollary of [strong_progress]... *)
  unfold normal_form. intros t H.
  assert (G : value t \/ exists t', t ==> t').
    SCase "Proof of assertion". apply strong_progress.
  inversion G.
    SCase "l". apply H0.
    SCase "r". apply ex_falso_quodlibet. apply H. assumption.  Qed.

Corollary nf_same_as_value : forall t,
  normal_form step t <-> value t.
Proof.
  split. apply nf_is_value. apply value_is_nf. Qed.

(** Why is this interesting?

    Because [value] is a syntactic concept -- it is defined by looking
    at the form of a term -- while [normal_form] is a semantic one --
    it is defined by looking at how the term steps.  It is not obvious
    that these concepts should coincide!

    Indeed, we could easily have written the definitions so that they
    would not coincide... *)

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

(** We might, for example, mistakenly define [value] so that it
    includes some terms that are not finished reducing. *)

Module Temp1.
(* Open an inner module so we can redefine value and step. *)

Inductive value : tm -> Prop :=
| v_const : forall n, value (C n)
| v_funny : forall t1 n2,                       (* <---- *)
              value (P t1 (C n2)).

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_PlusConstConst : forall n1 n2,
      P (C n1) (C n2) ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
      t1 ==> t1' ->
      P t1 t2 ==> P t1' t2
  | ST_Plus2 : forall v1 t2 t2',
      value v1 ->
      t2 ==> t2' ->
      P v1 t2 ==> P v1 t2'

  where " t '==>' t' " := (step t t').

(** **** Exercise: 3 stars, advanced (value_not_same_as_normal_form) *)
Lemma value_not_same_as_normal_form :
  exists v, value v /\ ~ normal_form step v.
Proof.
  exists (P (C 1) (C 2)).
  split.
  - apply v_funny.
  - unfold not, normal_form. intros.
    apply H.
    exists (C 3).
    apply ST_PlusConstConst.
Qed.

(** [] *)
End Temp1.

(* ##################################################### *)
(** Alternatively, we might mistakenly define [step] so that it
    permits something designated as a value to reduce further. *)

Module Temp2.

Inductive value : tm -> Prop :=
| v_const : forall n, value (C n).

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_Funny : forall n,                         (* <---- *)
      C n ==> P (C n) (C 0)
  | ST_PlusConstConst : forall n1 n2,
      P (C n1) (C n2) ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
      t1 ==> t1' ->
      P t1 t2 ==> P t1' t2
  | ST_Plus2 : forall v1 t2 t2',
      value v1 ->
      t2 ==> t2' ->
      P v1 t2 ==> P v1 t2'

  where " t '==>' t' " := (step t t').

(** **** Exercise: 2 stars, advanced (value_not_same_as_normal_form) *)
Lemma value_not_same_as_normal_form :
  exists v, value v /\ ~ normal_form step v.
Proof.
  exists (C 1).
  split.
  - apply v_const.
  - unfold normal_form, not. intros.
    apply H.
    exists (P (C 1) (C 0)).
    apply ST_Funny.
Qed.

(** [] *)
End Temp2.

(* ########################################################### *)
(** Finally, we might define [value] and [step] so that there is some
    term that is not a value but that cannot take a step in the [step]
    relation.  Such terms are said to be _stuck_. In this case this is
    caused by a mistake in the semantics, but we will also see
    situations where, even in a correct language definition, it makes
    sense to allow some terms to be stuck. *)

Module Temp3.

Inductive value : tm -> Prop :=
  | v_const : forall n, value (C n).

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_PlusConstConst : forall n1 n2,
      P (C n1) (C n2) ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
      t1 ==> t1' ->
      P t1 t2 ==> P t1' t2

  where " t '==>' t' " := (step t t').

(** (Note that [ST_Plus2] is missing.) *)

(** **** Exercise: 3 stars, advanced (value_not_same_as_normal_form') *)
Lemma value_not_same_as_normal_form :
  exists t, ~ value t /\ normal_form step t.
Proof.
  exists (P (C 0) (P (C 1) (C 2))).
  split.
  - unfold not. intros.
    inversion H.
  - unfold normal_form, not. intros.
    destruct H.
    inversion H; subst.
    inversion H3.
Qed.
(** [] *)

End Temp3.

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

Module Temp4.

(** Here is another very simple language whose terms, instead of being
    just plus and numbers, are just the booleans true and false and a
    conditional expression... *)

Inductive tm : Type :=
  | ttrue : tm
  | tfalse : tm
  | tif : tm -> tm -> tm -> tm.

Inductive value : tm -> Prop :=
  | v_true : value ttrue
  | v_false : value tfalse.

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_IfTrue : forall t1 t2,
      tif ttrue t1 t2 ==> t1
  | ST_IfFalse : forall t1 t2,
      tif tfalse t1 t2 ==> t2
  | ST_If : forall t1 t1' t2 t3,
      t1 ==> t1' ->
      tif t1 t2 t3 ==> tif t1' t2 t3

  where " t '==>' t' " := (step t t').

(** **** Exercise: 1 star (smallstep_bools) *)
(** Which of the following propositions are provable?  (This is just a
    thought exercise, but for an extra challenge feel free to prove
    your answers in Coq.) *)

Definition bool_step_prop1 :=
  tfalse ==> tfalse.

Lemma prop1_false :
  ~ (bool_step_prop1).
Proof.
  inversion 1.
Qed.

Definition bool_step_prop2 :=
     tif
       ttrue
       (tif ttrue ttrue ttrue)
       (tif tfalse tfalse tfalse)
  ==>
     ttrue.

Lemma prop2_false :
  ~ bool_step_prop2.
Proof.
  inversion 1.
Qed.

Definition bool_step_prop3 :=
     tif
       (tif ttrue ttrue ttrue)
       (tif ttrue ttrue ttrue)
       tfalse
   ==>
     tif
       ttrue
       (tif ttrue ttrue ttrue)
       tfalse.

Lemma prop3_true :
  bool_step_prop3.
Proof.
  apply ST_If.
  apply ST_IfTrue.
Qed.

(** [] *)

(** **** Exercise: 3 stars, optional (progress_bool) *)
(** Just as we proved a progress theorem for plus expressions, we can
    do so for boolean expressions, as well. *)

Theorem strong_progress : forall t,
  value t \/ (exists t', t ==> t').
Proof.
  intros. induction t.
  - left. apply v_true.
  - left. apply v_false.
  - right.
    destruct IHt1.
    + destruct t1.
      eexists. eapply ST_IfTrue.
      eexists. eapply ST_IfFalse.
      inversion H.
    + destruct H.
      eexists.
      eapply ST_If.
      eauto.
Qed.

(** [] *)

(** **** Exercise: 2 stars, optional (step_deterministic) *)
Theorem step_deterministic :
  deterministic step.
Proof.
  unfold deterministic. intros.
  generalize dependent y2.
  induction H; intros.
  - inversion H0; subst.
    reflexivity.
    inversion H4.
  - inversion H0; subst.
    reflexivity.
    inversion H4.
  - inversion H0; subst; try solve [inversion H].
    find_apply_hyp_hyp.
    f_equal.
    auto.
Qed.

(** [] *)

Module Temp5.

(** **** Exercise: 2 stars (smallstep_bool_shortcut) *)
(** Suppose we want to add a "short circuit" to the step relation for
    boolean expressions, so that it can recognize when the [then] and
    [else] branches of a conditional are the same value (either
    [ttrue] or [tfalse]) and reduce the whole conditional to this
    value in a single step, even if the guard has not yet been reduced
    to a value. For example, we would like this proposition to be
    provable:
         tif
            (tif ttrue ttrue ttrue)
            tfalse
            tfalse
     ==>
         tfalse.
*)

(** Write an extra clause for the step relation that achieves this
    effect and prove [bool_step_prop4]. *)

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_IfTrue : forall t1 t2,
      tif ttrue t1 t2 ==> t1
  | ST_IfFalse : forall t1 t2,
      tif tfalse t1 t2 ==> t2
  | ST_If : forall t1 t1' t2 t3,
      t1 ==> t1' ->
      tif t1 t2 t3 ==> tif t1' t2 t3
  | ST_ShortCircuit : forall t1 t2,
                    tif t1 t2 t2 ==> t2

  where " t '==>' t' " := (step t t').
(** [] *)

Definition bool_step_prop4 :=
         tif
            (tif ttrue ttrue ttrue)
            tfalse
            tfalse
     ==>
         tfalse.

Example bool_step_prop4_holds :
  bool_step_prop4.
Proof.
  apply ST_ShortCircuit.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (properties_of_altered_step) *)
(** It can be shown that the determinism and strong progress theorems
    for the step relation in the lecture notes also hold for the
    definition of step given above.  After we add the clause
    [ST_ShortCircuit]...

    - Is the [step] relation still deterministic?  Write yes or no and
      briefly (1 sentence) explain your answer.

      No.  Consider tif (tif ttrue ttrue ttrue) ttrue ttrue.  By ST_If, this
      steps to tif ttrue ttrue ttrue.  By ST_ShortCircuit, this steps to ttrue.

      Optional: prove your answer correct in Coq.
*)

(* FILL IN HERE *)
(**
   - Does a strong progress theorem hold? Write yes or no and
     briefly (1 sentence) explain your answer.

     Yes.  The additional step rule only provides an additonal step option
     for non-value terms, and does not step them into non-value stuck states.

     Optional: prove your answer correct in Coq.
*)

(* FILL IN HERE *)
(**
   - In general, is there any way we could cause strong progress to
     fail if we took away one or more constructors from the original
     step relation? Write yes or no and briefly (1 sentence) explain
     your answer.

     Yes.  Take away ST_IfTrue.  Then if a guard eventually steps to
     ttrue, then we are stuck.

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

End Temp5.
End Temp4.

(* ########################################################### *)
(** * Multi-Step Reduction *)

(** Until now, we've been working with the _single-step reduction_
    relation [==>], which formalizes the individual steps of an
    _abstract machine_ for executing programs.

    We can also use this machine to reduce programs to completion --
    to find out what final result they yield.  This can be formalized
    as follows:

    - First, we define a _multi-step reduction relation_ [==>*], which
      relates terms [t] and [t'] if [t] can reach [t'] by any number
      of single reduction steps (including zero steps!).

    - Then we define a "result" of a term [t] as a normal form that
      [t] can reach by multi-step reduction. *)

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

(** Since we'll want to reuse the idea of multi-step reduction many
    times in this and future chapters, let's take a little extra
    trouble here and define it generically.

    Given a relation [R], we define a relation [multi R], called the
    _multi-step closure of [R]_ as follows: *)

Inductive multi {X:Type} (R: relation X) : relation X :=
  | multi_refl  : forall (x : X), multi R x x
  | multi_step : forall (x y z : X),
                    R x y ->
                    multi R y z ->
                    multi R x z.

(** The effect of this definition is that [multi R] relates two
    elements [x] and [y] if either

       - [x = y], or else
       - there is some sequence [z1], [z2], ..., [zn]
         such that
           R x z1
           R z1 z2
           ...
           R zn y.

    Thus, if [R] describes a single-step of computation, [z1],
    ... [zn] is the sequence of intermediate steps of computation
    between [x] and [y].
*)

Tactic Notation "multi_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "multi_refl" | Case_aux c "multi_step" ].

(** We write [==>*] for the [multi step] relation -- i.e., the
    relation that relates two terms [t] and [t'] if we can get from
    [t] to [t'] using the [step] relation zero or more times. *)

Definition multistep := multi step.
Notation " t '==>*' t' " := (multistep t t') (at level 40).

(** The relation [multi R] has several crucial properties.

    First, it is obviously _reflexive_ (that is, [forall x, multi R x
    x]).  In the case of the [==>*] (i.e. [multi step]) relation, the
    intuition is that a term can execute to itself by taking zero
    steps of execution.

    Second, it contains [R] -- that is, single-step executions are a
    particular case of multi-step executions.  (It is this fact that
    justifies the word "closure" in the term "multi-step closure of
    [R].") *)

Theorem multi_R : forall (X:Type) (R:relation X) (x y : X),
       R x y -> (multi R) x y.
Proof.
  intros X R x y H.
  apply multi_step with y. apply H. apply multi_refl.   Qed.

(** Third, [multi R] is _transitive_. *)

Theorem multi_trans :
  forall (X:Type) (R: relation X) (x y z : X),
      multi R x y  ->
      multi R y z ->
      multi R x z.
Proof.
  intros X R x y z G H.
  multi_cases (induction G) Case.
    Case "multi_refl". assumption.
    Case "multi_step".
      apply multi_step with y. assumption.
      apply IHG. assumption.  Qed.

(** That is, if [t1==>*t2] and [t2==>*t3], then [t1==>*t3]. *)

(* ########################################################### *)
(** ** Examples *)

Lemma test_multistep_1:
      P
        (P (C 0) (C 3))
        (P (C 2) (C 4))
   ==>*
      C ((0 + 3) + (2 + 4)).
Proof.
  apply multi_step with
            (P
                (C (0 + 3))
                (P (C 2) (C 4))).
  apply ST_Plus1. apply ST_PlusConstConst.
  apply multi_step with
            (P
                (C (0 + 3))
                (C (2 + 4))).
  apply ST_Plus2. apply v_const.
  apply ST_PlusConstConst.
  apply multi_R.
  apply ST_PlusConstConst. Qed.

(** Here's an alternate proof that uses [eapply] to avoid explicitly
    constructing all the intermediate terms. *)

Lemma test_multistep_1':
      P
        (P (C 0) (C 3))
        (P (C 2) (C 4))
  ==>*
      C ((0 + 3) + (2 + 4)).
Proof.
  eapply multi_step. apply ST_Plus1. apply ST_PlusConstConst.
  eapply multi_step. apply ST_Plus2. apply v_const.
  apply ST_PlusConstConst.
  eapply multi_step. apply ST_PlusConstConst.
  apply multi_refl.  Qed.

(** **** Exercise: 1 star, optional (test_multistep_2) *)
Lemma test_multistep_2:
  C 3 ==>* C 3.
Proof.
  apply multi_refl.
Qed.
(** [] *)

(** **** Exercise: 1 star, optional (test_multistep_3) *)
Lemma test_multistep_3:
      P (C 0) (C 3)
   ==>*
      P (C 0) (C 3).
Proof.
  apply multi_refl.
Qed.
(** [] *)

(** **** Exercise: 2 stars (test_multistep_4) *)
Lemma test_multistep_4:
      P
        (C 0)
        (P
          (C 2)
          (P (C 0) (C 3)))
  ==>*
      P
        (C 0)
        (C (2 + (0 + 3))).
Proof.
  eapply multi_step.
  apply ST_Plus2.
  apply v_const.
  apply ST_Plus2.
  apply v_const.
  apply ST_PlusConstConst.
  apply multi_R.
  apply ST_Plus2.
  apply v_const.
  apply ST_PlusConstConst.
Qed.

(** [] *)

(* ########################################################### *)
(** ** Normal Forms Again *)

(** If [t] reduces to [t'] in zero or more steps and [t'] is a
    normal form, we say that "[t'] is a normal form of [t]." *)

Definition step_normal_form := normal_form step.

Definition normal_form_of (t t' : tm) :=
  (t ==>* t' /\ step_normal_form t').

(** We have already seen that, for our language, single-step reduction is
    deterministic -- i.e., a given term can take a single step in
    at most one way.  It follows from this that, if [t] can reach
    a normal form, then this normal form is unique.  In other words, we
    can actually pronounce [normal_form t t'] as "[t'] is _the_
    normal form of [t]." *)

(** **** Exercise: 3 stars, optional (normal_forms_unique) *)
Theorem normal_forms_unique:
  deterministic normal_form_of.
Proof.
  unfold deterministic. unfold normal_form_of.  intros x y1 y2 P1 P2.
  inversion P1 as [P11 P12]; clear P1. inversion P2 as [P21 P22]; clear P2.
  generalize dependent y2.
  (* We recommend using this initial setup as-is! *)
  induction P11; intros.
  - unfold step_normal_form, normal_form in *.
    inversion P21; subst; try reflexivity.
    exfalso.
    apply P12.
    eexists; eauto.
  - concludes.
    apply IHP11; auto.
    inversion P21; subst.
    + exfalso.
      apply P22.
      eexists; eauto.
    + replace y0 with y in *. auto.
      apply (step_deterministic x y y0); auto.
Qed.

(** [] *)

(** Indeed, something stronger is true for this language (though not
    for all languages): the reduction of _any_ term [t] will
    eventually reach a normal form -- i.e., [normal_form_of] is a
    _total_ function.  Formally, we say the [step] relation is
    _normalizing_. *)

Definition normalizing {X:Type} (R:relation X) :=
  forall t, exists t',
    (multi R) t t' /\ normal_form R t'.

(** To prove that [step] is normalizing, we need a couple of lemmas.

    First, we observe that, if [t] reduces to [t'] in many steps, then
    the same sequence of reduction steps within [t] is also possible
    when [t] appears as the left-hand child of a [P] node, and
    similarly when [t] appears as the right-hand child of a [P]
    node whose left-hand child is a value. *)

Lemma multistep_congr_1 : forall t1 t1' t2,
     t1 ==>* t1' ->
     P t1 t2 ==>* P t1' t2.
Proof.
  intros t1 t1' t2 H. multi_cases (induction H) Case.
    Case "multi_refl". apply multi_refl.
    Case "multi_step". apply multi_step with (P y t2).
        apply ST_Plus1. apply H.
        apply IHmulti.  Qed.

(** **** Exercise: 2 stars (multistep_congr_2) *)
Lemma multistep_congr_2 : forall t1 t2 t2',
     value t1 ->
     t2 ==>* t2' ->
     P t1 t2 ==>* P t1 t2'.
Proof.
  intros. induction H0.
  - apply multi_refl.
  - eapply multi_step.
    apply ST_Plus2; eauto.
    auto.
Qed.

(** [] *)

(** _Theorem_: The [step] function is normalizing -- i.e., for every
    [t] there exists some [t'] such that [t] steps to [t'] and [t'] is
    a normal form.

    _Proof sketch_: By induction on terms.  There are two cases to
    consider:

    - [t = C n] for some [n].  Here [t] doesn't take a step,
      and we have [t' = t].  We can derive the left-hand side by
      reflexivity and the right-hand side by observing (a) that values
      are normal forms (by [nf_same_as_value]) and (b) that [t] is a
      value (by [v_const]).

    - [t = P t1 t2] for some [t1] and [t2].  By the IH, [t1] and
      [t2] have normal forms [t1'] and [t2'].  Recall that normal
      forms are values (by [nf_same_as_value]); we know that [t1' =
      C n1] and [t2' = C n2], for some [n1] and [n2].
      We can combine the [==>*] derivations for [t1] and [t2] to prove
      that [P t1 t2] reduces in many steps to [C (n1 + n2)].

      It is clear that our choice of [t' = C (n1 + n2)] is a
      value, which is in turn a normal form. [] *)

Theorem step_normalizing :
  normalizing step.
Proof.
  unfold normalizing.
  tm_cases (induction t) Case.
    Case "C".
      exists (C n).
      split.
      SCase "l". apply multi_refl.
      SCase "r".
        (* We can use [rewrite] with "iff" statements, not
           just equalities: *)
        rewrite nf_same_as_value. apply v_const.
    Case "P".
      inversion IHt1 as [t1' H1]; clear IHt1. inversion IHt2 as [t2' H2]; clear IHt2.
      inversion H1 as [H11 H12]; clear H1. inversion H2 as [H21 H22]; clear H2.
      rewrite nf_same_as_value in H12. rewrite nf_same_as_value in H22.
      inversion H12 as [n1]. inversion H22 as [n2].
      rewrite <- H in H11.
      rewrite <- H0 in H21.
      exists (C (n1 + n2)).
      split.
        SCase "l".
          apply multi_trans with (P (C n1) t2).
          apply multistep_congr_1. apply H11.
          apply multi_trans with
             (P (C n1) (C n2)).
          apply multistep_congr_2. apply v_const. apply H21.
          apply multi_R. apply ST_PlusConstConst.
        SCase "r".
          rewrite nf_same_as_value. apply v_const.  Qed.

(* ########################################################### *)
(** ** Equivalence of Big-Step and Small-Step Reduction *)

(** Having defined the operational semantics of our tiny programming
    language in two different styles, it makes sense to ask whether
    these definitions actually define the same thing!  They do, though
    it takes a little work to show it.  (The details are left as an
    exercise). *)

(** **** Exercise: 3 stars (eval__multistep) *)

Theorem eval__multistep : forall t n,
  t || n -> t ==>* C n.

(** The key idea behind the proof comes from the following picture:
       P t1 t2 ==>            (by ST_Plus1)
       P t1' t2 ==>           (by ST_Plus1)
       P t1'' t2 ==>          (by ST_Plus1)
       ...
       P (C n1) t2 ==>        (by ST_Plus2)
       P (C n1) t2' ==>       (by ST_Plus2)
       P (C n1) t2'' ==>      (by ST_Plus2)
       ...
       P (C n1) (C n2) ==>    (by ST_PlusConstConst)
       C (n1 + n2)
    That is, the multistep reduction of a term of the form [P t1 t2]
    proceeds in three phases:
       - First, we use [ST_Plus1] some number of times to reduce [t1]
         to a normal form, which must (by [nf_same_as_value]) be a
         term of the form [C n1] for some [n1].
       - Next, we use [ST_Plus2] some number of times to reduce [t2]
         to a normal form, which must again be a term of the form [C
         n2] for some [n2].
       - Finally, we use [ST_PlusConstConst] one time to reduce [P (C
         n1) (C n2)] to [C (n1 + n2)]. *)

(** To formalize this intuition, you'll need to use the congruence
    lemmas from above (you might want to review them now, so that
    you'll be able to recognize when they are useful), plus some basic
    properties of [==>*]: that it is reflexive, transitive, and
    includes [==>]. *)

Proof.
  intros. induction H.
  - apply multi_refl.
  - eapply multi_trans.
    apply multistep_congr_1; eauto.
    eapply multi_trans.
    apply multistep_congr_2; eauto; try apply v_const.
    apply multi_R.
    apply ST_PlusConstConst.
Qed.

(** [] *)

(** **** Exercise: 3 stars, advanced (eval__multistep_inf) *)
(** Write a detailed informal version of the proof of [eval__multistep].

t || n -> t ==>* C n

Proceed by induction on [ t || n ].

Suppose in the base case that [ t = C n ].  Then we have that [ t ==>* C n ]
by the fact that [ ==>* ] is a reflexive relation.

Now suppose that [ t = P t1 t2 ], [ n = n1 + n2 ], and we have that
[ t1 || n1 -> t2 ==>* C n1 ] and [ t2 || n2 -> t2 ==>* C n2 ].  To show
that [ P t1 t2 ==>* C (n1 + n2) ], it suffices by transitivity to show
that [ P t1 t2 ==>* P (C n1) (C n2) ] and [ P (C n1) (C n2) ==>* C (n1 + n2) ].
The latter follows by the fact that [ ==>* ] contains [ ==> ] and the
[ ST_PlusConstConst ] constructor.  The former follows by applications of
our congruence lemmas [ multistep_congr_1 ] and [ multistep_congr_2 ].

[]
*)
(** For the other direction, we need one lemma, which establishes a
    relation between single-step reduction and big-step evaluation. *)

(** **** Exercise: 3 stars (step__eval) *)
Lemma step__eval : forall t t' n,
     t ==> t' ->
     t' || n ->
     t || n.
Proof.
(*
  intros. generalize dependent t.
  induction H0; intros.
  - inversion H; subst.
    apply E_Plus; apply E_Const.
  - SearchAbout eval.
*)
  intros t t' n Hs. generalize dependent n.
  induction Hs; intros.
  - inversion H; subst.
    apply E_Plus; apply E_Const.
  - inversion H; subst.
    apply E_Plus; auto.
  - inversion H0; subst.
    apply E_Plus; auto.
Qed.

(** [] *)

(** The fact that small-step reduction implies big-step is now
    straightforward to prove, once it is stated correctly.

    The proof proceeds by induction on the multi-step reduction
    sequence that is buried in the hypothesis [normal_form_of t t']. *)
(** Make sure you understand the statement before you start to
    work on the proof.  *)

(** **** Exercise: 3 stars (multistep__eval) *)
Theorem multistep__eval : forall t t',
  normal_form_of t t' -> exists n, t' = C n /\ t || n.
Proof.
  unfold normal_form_of, step_normal_form.
  intros. intuition.
  find_apply_lem_hyp nf_same_as_value.
  find_value_invc.
  exists n.
  split; try reflexivity.
  remember (C n) as t'.
  induction H0; subst.
  - apply E_Const.
  - concludes.
    eapply step__eval; eauto.
Qed.

(** [] *)

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

(** **** Exercise: 3 stars, optional (interp_tm) *)
(** Remember that we also defined big-step evaluation of [tm]s as a
    function [evalF].  Prove that it is equivalent to the existing
    semantics.

    Hint: we just proved that [eval] and [multistep] are
    equivalent, so logically it doesn't matter which you choose.
    One will be easier than the other, though!  *)

Theorem evalF_eval : forall t n,
  evalF t = n <-> t || n.
Proof.
  split; intros.
  - generalize dependent n.
    induction t; intros.
    + simpl in *; subst. apply E_Const.
    + simpl in *; subst.
      apply E_Plus; auto.
  - induction H.
    + reflexivity.
    + simpl. congruence.
Qed.

(** [] *)

(** **** Exercise: 4 stars (combined_properties) *)
(** We've considered the arithmetic and conditional expressions
    separately.  This exercise explores how the two interact. *)

Module Combined.

Inductive tm : Type :=
  | C : nat -> tm
  | P : tm -> tm -> tm
  | ttrue : tm
  | tfalse : tm
  | tif : tm -> tm -> tm -> tm.

Tactic Notation "tm_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "C" | Case_aux c "P"
  | Case_aux c "ttrue" | Case_aux c "tfalse" | Case_aux c "tif" ].

Inductive value : tm -> Prop :=
  | v_const : forall n, value (C n)
  | v_true : value ttrue
  | v_false : value tfalse.

Reserved Notation " t '==>' t' " (at level 40).

Inductive step : tm -> tm -> Prop :=
  | ST_PlusConstConst : forall n1 n2,
      P (C n1) (C n2) ==> C (n1 + n2)
  | ST_Plus1 : forall t1 t1' t2,
      t1 ==> t1' ->
      P t1 t2 ==> P t1' t2
  | ST_Plus2 : forall v1 t2 t2',
      value v1 ->
      t2 ==> t2' ->
      P v1 t2 ==> P v1 t2'
  | ST_IfTrue : forall t1 t2,
      tif ttrue t1 t2 ==> t1
  | ST_IfFalse : forall t1 t2,
      tif tfalse t1 t2 ==> t2
  | ST_If : forall t1 t1' t2 t3,
      t1 ==> t1' ->
      tif t1 t2 t3 ==> tif t1' t2 t3

  where " t '==>' t' " := (step t t').

Tactic Notation "step_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "ST_PlusConstConst"
  | Case_aux c "ST_Plus1" | Case_aux c "ST_Plus2"
  | Case_aux c "ST_IfTrue" | Case_aux c "ST_IfFalse" | Case_aux c "ST_If" ].

(** Earlier, we separately proved for both plus- and if-expressions...

    - that the step relation was deterministic, and

    - a strong progress lemma, stating that every term is either a
      value or can take a step.

    Prove or disprove these two properties for the combined language. *)

Ltac find_value_invc :=
  match goal with
    | [ H : value ?t |- _ ] => inversion H; subst; clear H
  end.

Ltac find_step_invc :=
  match goal with
    | [ H : (C ?n) ==> ?t |- _ ] => inversion H
    | [ H : ttrue ==> ?t |- _ ] => inversion H
    | [ H : tfalse ==> ?t |- _ ] => inversion H
    | [ H : ?t ==> ?t' |- _ ] => inversion H; subst; clear H
  end.

Theorem step_deterministic :
  deterministic step.
Proof.
  unfold deterministic.
  intros. generalize dependent y2.
  induction H; intros.
  - find_step_invc; try solve [find_step_invc].
    reflexivity.
  - inversion H0; subst; try find_value_invc; try solve [find_step_invc].
    rewrite (IHstep t1'0); auto.
  - inversion H1; subst; try find_value_invc;
      try solve [find_step_invc];
      f_equal; auto.
  - find_step_invc. reflexivity. find_step_invc.
  - find_step_invc. reflexivity. find_step_invc.
  - inversion H0; subst; try solve [find_step_invc].
    f_equal. auto.
Qed.

(** [] *)

End Combined.

(* ########################################################### *)
(** * Small-Step Imp *)

(** For a more serious example, here is the small-step version of the
    Imp operational semantics.  *)

(** The small-step evaluation relations for arithmetic and boolean
    expressions are straightforward extensions of the tiny language
    we've been working up to now.  To make them easier to read, we
    introduce the symbolic notations [==>a] and [==>b], respectively,
    for the arithmetic and boolean step relations. *)

Inductive aval : aexp -> Prop :=
  av_num : forall n, aval (ANum n).

(** We are not actually going to bother to define boolean
    values, since they aren't needed in the definition of [==>b]
    below (why?), though they might be if our language were a bit
    larger (why?). *)

Reserved Notation " t '/' st '==>a' t' " (at level 40, st at level 39).

Inductive astep : state -> aexp -> aexp -> Prop :=
  | AS_Id : forall st i,
      AId i / st ==>a ANum (st i)
  | AS_Plus : forall st n1 n2,
      APlus (ANum n1) (ANum n2) / st ==>a ANum (n1 + n2)
  | AS_Plus1 : forall st a1 a1' a2,
      a1 / st ==>a a1' ->
      (APlus a1 a2) / st ==>a (APlus a1' a2)
  | AS_Plus2 : forall st v1 a2 a2',
      aval v1 ->
      a2 / st ==>a a2' ->
      (APlus v1 a2) / st ==>a (APlus v1 a2')
(*  | AS_Plus2 : forall n st a2 a2',
                 a2 / st ==>a a2' ->
                 (APlus (ANum n) a2) / st ==>a (APlus (ANum n) a2') *)
  | AS_Minus : forall st n1 n2,
      (AMinus (ANum n1) (ANum n2)) / st ==>a (ANum (minus n1 n2))
  | AS_Minus1 : forall st a1 a1' a2,
      a1 / st ==>a a1' ->
      (AMinus a1 a2) / st ==>a (AMinus a1' a2)
  | AS_Minus2 : forall st v1 a2 a2',
      aval v1 ->
      a2 / st ==>a a2' ->
      (AMinus v1 a2) / st ==>a (AMinus v1 a2')
  | AS_Mult : forall st n1 n2,
      (AMult (ANum n1) (ANum n2)) / st ==>a (ANum (mult n1 n2))
  | AS_Mult1 : forall st a1 a1' a2,
      a1 / st ==>a a1' ->
      (AMult (a1) (a2)) / st ==>a (AMult (a1') (a2))
  | AS_Mult2 : forall st v1 a2 a2',
      aval v1 ->
      a2 / st ==>a a2' ->
      (AMult v1 a2) / st ==>a (AMult v1 a2')

    where " t '/' st '==>a' t' " := (astep st t t').

  Reserved Notation " t '/' st '==>b' t' " (at level 40, st at level 39).

  Inductive bstep : state -> bexp -> bexp -> Prop :=
  | BS_Eq : forall st n1 n2,
      (BEq (ANum n1) (ANum n2)) / st ==>b
      (if (beq_nat n1 n2) then BTrue else BFalse)
  | BS_Eq1 : forall st a1 a1' a2,
      a1 / st ==>a a1' ->
      (BEq a1 a2) / st ==>b (BEq a1' a2)
  | BS_Eq2 : forall st v1 a2 a2',
      aval v1 ->
      a2 / st ==>a a2' ->
      (BEq v1 a2) / st ==>b (BEq v1 a2')
  | BS_LtEq : forall st n1 n2,
      (BLe (ANum n1) (ANum n2)) / st ==>b
               (if (ble_nat n1 n2) then BTrue else BFalse)
  | BS_LtEq1 : forall st a1 a1' a2,
      a1 / st ==>a a1' ->
      (BLe a1 a2) / st ==>b (BLe a1' a2)
  | BS_LtEq2 : forall st v1 a2 a2',
      aval v1 ->
      a2 / st ==>a a2' ->
      (BLe v1 a2) / st ==>b (BLe v1 (a2'))
  | BS_NotTrue : forall st,
      (BNot BTrue) / st ==>b BFalse
  | BS_NotFalse : forall st,
      (BNot BFalse) / st ==>b BTrue
  | BS_NotStep : forall st b1 b1',
      b1 / st ==>b b1' ->
      (BNot b1) / st ==>b (BNot b1')
  | BS_AndTrueTrue : forall st,
      (BAnd BTrue BTrue) / st ==>b BTrue
  | BS_AndTrueFalse : forall st,
      (BAnd BTrue BFalse) / st ==>b BFalse
  | BS_AndFalse : forall st b2,
      (BAnd BFalse b2) / st ==>b BFalse
  | BS_AndTrueStep : forall st b2 b2',
      b2 / st ==>b b2' ->
      (BAnd BTrue b2) / st ==>b (BAnd BTrue b2')
  | BS_AndStep : forall st b1 b1' b2,
      b1 / st ==>b b1' ->
      (BAnd b1 b2) / st ==>b (BAnd b1' b2)

  where " t '/' st '==>b' t' " := (bstep st t t').

(** The semantics of commands is the interesting part.  We need two
    small tricks to make it work:

       - We use [SKIP] as a "command value" -- i.e., a command that
         has reached a normal form.

            - An assignment command reduces to [SKIP] (and an updated
              state).

            - The sequencing command waits until its left-hand
              subcommand has reduced to [SKIP], then throws it away so
              that reduction can continue with the right-hand
              subcommand.

       - We reduce a [WHILE] command by transforming it into a
         conditional followed by the same [WHILE].  *)

(** (There are other ways of achieving the effect of the latter
   trick, but they all share the feature that the original [WHILE]
   command needs to be saved somewhere while a single copy of the loop
   body is being evaluated.) *)

Reserved Notation " t '/' st '==>' t' '/' st' "
                  (at level 40, st at level 39, t' at level 39).

Inductive cstep : (com * state) -> (com * state) -> Prop :=
  | CS_AssStep : forall st i a a',
      a / st ==>a a' ->
      (i ::= a) / st ==> (i ::= a') / st
  | CS_Ass : forall st i n,
      (i ::= (ANum n)) / st ==> SKIP / (update st i n)
  | CS_SeqStep : forall st c1 c1' st' c2,
      c1 / st ==> c1' / st' ->
      (c1 ;; c2) / st ==> (c1' ;; c2) / st'
  | CS_SeqFinish : forall st c2,
      (SKIP ;; c2) / st ==> c2 / st
  | CS_IfTrue : forall st c1 c2,
      IFB BTrue THEN c1 ELSE c2 FI / st ==> c1 / st
  | CS_IfFalse : forall st c1 c2,
      IFB BFalse THEN c1 ELSE c2 FI / st ==> c2 / st
  | CS_IfStep : forall st b b' c1 c2,
      b / st ==>b b' ->
      IFB b THEN c1 ELSE c2 FI / st ==> (IFB b' THEN c1 ELSE c2 FI) / st
  | CS_While : forall st b c1,
          (WHILE b DO c1 END) / st
      ==> (IFB b THEN (c1;; (WHILE b DO c1 END)) ELSE SKIP FI) / st

  where " t '/' st '==>' t' '/' st' " := (cstep (t,st) (t',st')).

(* ########################################################### *)
(** * Concurrent Imp *)

(** Finally, to show the power of this definitional style, let's
    enrich Imp with a new form of command that runs two subcommands in
    parallel and terminates when both have terminated.  To reflect the
    unpredictability of scheduling, the actions of the subcommands may
    be interleaved in any order, but they share the same memory and
    can communicate by reading and writing the same variables. *)

Module CImp.

Inductive com : Type :=
  | CSkip : com
  | CAss : id -> aexp -> com
  | CSeq : com -> com -> com
  | CIf : bexp -> com -> com -> com
  | CWhile : bexp -> com -> com
  (* New: *)
  | CPar : com -> com -> com.

Tactic Notation "com_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "SKIP" | Case_aux c "::=" | Case_aux c ";"
  | Case_aux c "IFB" | Case_aux c "WHILE" | Case_aux c "PAR" ].

Notation "'SKIP'" :=
  CSkip.
Notation "x '::=' a" :=
  (CAss x a) (at level 60).
Notation "c1 ;; c2" :=
  (CSeq c1 c2) (at level 80, right associativity).
Notation "'WHILE' b 'DO' c 'END'" :=
  (CWhile b c) (at level 80, right associativity).
Notation "'IFB' b 'THEN' c1 'ELSE' c2 'FI'" :=
  (CIf b c1 c2) (at level 80, right associativity).
Notation "'PAR' c1 'WITH' c2 'END'" :=
  (CPar c1 c2) (at level 80, right associativity).

Inductive cstep : (com * state)  -> (com * state) -> Prop :=
    (* Old part *)
  | CS_AssStep : forall st i a a',
      a / st ==>a a' ->
      (i ::= a) / st ==> (i ::= a') / st
  | CS_Ass : forall st i n,
      (i ::= (ANum n)) / st ==> SKIP / (update st i n)
  | CS_SeqStep : forall st c1 c1' st' c2,
      c1 / st ==> c1' / st' ->
      (c1 ;; c2) / st ==> (c1' ;; c2) / st'
  | CS_SeqFinish : forall st c2,
      (SKIP ;; c2) / st ==> c2 / st
  | CS_IfTrue : forall st c1 c2,
      (IFB BTrue THEN c1 ELSE c2 FI) / st ==> c1 / st
  | CS_IfFalse : forall st c1 c2,
      (IFB BFalse THEN c1 ELSE c2 FI) / st ==> c2 / st
  | CS_IfStep : forall st b b' c1 c2,
      b /st ==>b b' ->
      (IFB b THEN c1 ELSE c2 FI) / st ==> (IFB b' THEN c1 ELSE c2 FI) / st
  | CS_While : forall st b c1,
      (WHILE b DO c1 END) / st ==>
               (IFB b THEN (c1;; (WHILE b DO c1 END)) ELSE SKIP FI) / st
    (* New part: *)
  | CS_Par1 : forall st c1 c1' c2 st',
      c1 / st ==> c1' / st' ->
      (PAR c1 WITH c2 END) / st ==> (PAR c1' WITH c2 END) / st'
  | CS_Par2 : forall st c1 c2 c2' st',
      c2 / st ==> c2' / st' ->
      (PAR c1 WITH c2 END) / st ==> (PAR c1 WITH c2' END) / st'
  | CS_ParDone : forall st,
      (PAR SKIP WITH SKIP END) / st ==> SKIP / st
  where " t '/' st '==>' t' '/' st' " := (cstep (t,st) (t',st')).

Definition cmultistep := multi cstep.

Notation " t '/' st '==>*' t' '/' st' " :=
   (multi cstep  (t,st) (t',st'))
   (at level 40, st at level 39, t' at level 39).

(** Among the many interesting properties of this language is the fact
    that the following program can terminate with the variable [X] set
    to any value... *)

Definition par_loop : com :=
  PAR
    Y ::= ANum 1
  WITH
    WHILE BEq (AId Y) (ANum 0) DO
      X ::= APlus (AId X) (ANum 1)
    END
  END.

(** In particular, it can terminate with [X] set to [0]: *)

Example par_loop_example_0:
  exists st',
       par_loop / empty_state  ==>* SKIP / st'
    /\ st' X = 0.
Proof.
  eapply ex_intro. split.
  unfold par_loop.
  eapply multi_step. apply CS_Par1.
    apply CS_Ass.
  eapply multi_step. apply CS_Par2. apply CS_While.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq. simpl.
  eapply multi_step. apply CS_Par2. apply CS_IfFalse.
  eapply multi_step. apply CS_ParDone.
  eapply multi_refl.
  reflexivity. Qed.

(** It can also terminate with [X] set to [2]: *)

Example par_loop_example_2:
  exists st',
       par_loop / empty_state ==>* SKIP / st'
    /\ st' X = 2.
Proof.
  eapply ex_intro. split.
  eapply multi_step. apply CS_Par2. apply CS_While.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq. simpl.
  eapply multi_step. apply CS_Par2. apply CS_IfTrue.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_Ass.
  eapply multi_step. apply CS_Par2. apply CS_SeqFinish.

  eapply multi_step. apply CS_Par2. apply CS_While.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq. simpl.
  eapply multi_step. apply CS_Par2. apply CS_IfTrue.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus.
  eapply multi_step. apply CS_Par2. apply CS_SeqStep.
    apply CS_Ass.

  eapply multi_step. apply CS_Par1. apply CS_Ass.
  eapply multi_step. apply CS_Par2. apply CS_SeqFinish.
  eapply multi_step. apply CS_Par2. apply CS_While.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq. simpl.
  eapply multi_step. apply CS_Par2. apply CS_IfFalse.
  eapply multi_step. apply CS_ParDone.
  eapply multi_refl.
  reflexivity. Qed.

(** More generally... *)

(** **** Exercise: 3 stars, optional *)

Theorem multistep_step :
  forall c1 c2 st1 st2,
    c1 / st1 ==> c2 / st2 ->
    c1 / st1 ==>* c2 / st2.
Proof.
  intros.
  apply multi_R; auto.
Qed.

Theorem multistep_trans :
  forall c1 c2 c3 st1 st2 st3,
    c1 / st1 ==>* c2 / st2 ->
    c2 / st2 ==>* c3 / st3 ->
    c1 / st1 ==>* c3 / st3.
Proof.
  intros.
  eapply multi_trans; eauto.
Qed.

Theorem CS_Seq_congruence :
  forall c1 c1' c2 st st',
    c1 / st ==>* c1' / st' ->
    (c1 ;; c2 ) / st ==>* (c1' ;; c2) / st'.
Proof.
  intros.
  remember (c1, st) as x.
  remember (c1', st') as x'.
  generalize dependent st'.
  generalize dependent c1'.
  generalize dependent st.
  generalize dependent c1.
  induction H; intros; subst.
  - inversion Heqx'; subst.
    apply multi_refl.
  - apply multi_step with (y0 := ( (fst y) ;; c2 , snd y)).
    + apply CS_SeqStep.
      replace (fst y, snd y) with y;
      auto using surjective_pairing.
    + apply IHmulti;
      auto using surjective_pairing.
Qed.

Theorem CS_Par1_congruence :
  forall c1 c1' c2 st st',
    c1 / st ==>* c1' / st' ->
    (PAR c1 WITH c2 END) / st ==>* (PAR c1' WITH c2 END) / st'.
Proof.
  intros.
  remember (c1, st) as x.
  remember (c1', st') as x'.
  generalize dependent st'.
  generalize dependent c1'.
  generalize dependent st.
  generalize dependent c1.
  induction H; intros; subst.
  - inversion Heqx'; subst.
    apply multi_refl.
  - apply multi_step with (y0 := (PAR (fst y) WITH c2 END, snd y)).
    + apply CS_Par1.
      replace (fst y, snd y) with y;
      auto using surjective_pairing.
    + apply IHmulti;
      auto using surjective_pairing.
Qed.

Theorem CS_Par2_congruence :
  forall c1 c2 c2' st st',
    c2 / st ==>* c2' / st' ->
    (PAR c1 WITH c2 END) / st ==>* (PAR c1 WITH c2' END) / st'.
Proof.
  intros.
  remember (c2, st) as x.
  remember (c2', st') as x'.
  generalize dependent st'.
  generalize dependent c2'.
  generalize dependent st.
  generalize dependent c2.
  induction H; intros; subst.
  - inversion Heqx'; subst.
    apply multi_refl.
  - apply multi_step with (y0 := (PAR c1 WITH (fst y) END, snd y)).
    + apply CS_Par2.
      replace (fst y, snd y) with y;
      auto using surjective_pairing.
    + apply IHmulti;
      auto using surjective_pairing.
Qed.

Lemma par_body_n__Sn : forall n st,
  st X = n /\ st Y = 0 ->
  par_loop / st ==>* par_loop / (update st X (S n)).
Proof.
  intuition.
  unfold par_loop.
  apply CS_Par2_congruence.
  eapply multi_step. apply CS_While.
  eapply multi_step. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id.
  eapply multi_step. apply CS_IfStep.
    apply BS_Eq. find_rewrite. simpl.
  eapply multi_step. apply CS_IfTrue.
  eapply multi_step. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus1. apply AS_Id.
  eapply multi_step. apply CS_SeqStep.
    apply CS_AssStep. apply AS_Plus.
  eapply multi_step. apply CS_SeqStep.
    apply CS_Ass.
  eapply multi_step. apply CS_SeqFinish.
  find_rewrite. rewrite plus_comm.
  apply multi_refl.
Qed.

(** [] *)

(** **** Exercise: 3 stars, optional *)
Lemma par_body_n : forall n st,
  st X = 0 /\ st Y = 0 ->
  exists st',
    par_loop / st ==>*  par_loop / st' /\ st' X = n /\ st' Y = 0.
Proof.
  admit.
Qed.
(** [] *)

(** ... the above loop can exit with [X] having any value
    whatsoever. *)

Theorem par_loop_any_X:
  forall n, exists st',
    par_loop / empty_state ==>*  SKIP / st'
    /\ st' X = n.
Proof.
  intros n.
  destruct (par_body_n n empty_state).
    split; unfold update; reflexivity.

  rename x into st.
  inversion H as [H' [HX HY]]; clear H.
  exists (update st Y 1). split.
  eapply multi_trans with (par_loop,st). apply H'.
  eapply multi_step. apply CS_Par1. apply CS_Ass.
  eapply multi_step. apply CS_Par2. apply CS_While.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq1. apply AS_Id. rewrite update_eq.
  eapply multi_step. apply CS_Par2. apply CS_IfStep.
    apply BS_Eq. simpl.
  eapply multi_step. apply CS_Par2. apply CS_IfFalse.
  eapply multi_step. apply CS_ParDone.
  apply multi_refl.

  rewrite update_neq. assumption. intro X; inversion X.
Qed.

End CImp.

(* ########################################################### *)
(** * A Small-Step Stack Machine *)

(** Last example: a small-step semantics for the stack machine example
    from Imp.v. *)

Definition stack := list nat.
Definition prog  := list sinstr.

Inductive stack_step : state -> prog * stack -> prog * stack -> Prop :=
  | SS_Push : forall st stk n p',
    stack_step st (SPush n :: p', stk)      (p', n :: stk)
  | SS_Load : forall st stk i p',
    stack_step st (SLoad i :: p', stk)      (p', st i :: stk)
  | SS_Plus : forall st stk n m p',
    stack_step st (SPlus :: p', n::m::stk)  (p', (m+n)::stk)
  | SS_Minus : forall st stk n m p',
    stack_step st (SMinus :: p', n::m::stk) (p', (m-n)::stk)
  | SS_Mult : forall st stk n m p',
    stack_step st (SMult :: p', n::m::stk)  (p', (m*n)::stk).

Theorem stack_step_deterministic : forall st,
  deterministic (stack_step st).
Proof.
  unfold deterministic. intros st x y1 y2 H1 H2.
  induction H1; inversion H2; reflexivity.
Qed.

Definition stack_multistep st := multi (stack_step st).

(** **** Exercise: 3 stars, advanced (compiler_is_correct) *)
(** Remember the definition of [compile] for [aexp] given in the
    [Imp] chapter. We want now to prove [compile] correct with respect
    to the stack machine.

    State what it means for the compiler to be correct according to
    the stack machine small step semantics and then prove it. *)

Definition compiler_is_correct_statement : Prop :=
  forall (e : aexp) (st : state),
    stack_multistep st (s_compile e, []) ([], [aeval st e]).

Ltac find_stackmultistep_invc :=
  match goal with
    | [ H : stack_multistep ?st (?i :: ?p, ?stk) (?p', ?stk') |- _ ] => inversion H; subst; clear H
    | [ H : stack_multistep ?st (?p, ?stk) (?p', ?stk') |- _ ] => inversion H; subst; clear H
  end.

Ltac find_stackstep_invc :=
  match goal with
    | [ H : stack_step ?st (?i :: ?p, ?stk) ?x |- _ ]  => inversion H; subst; clear H
  end.

Lemma stack_step_app :
  forall (p1 p2 : prog) (stk1 stk2 stk3 : stack) (st : state),
    stack_multistep st (p1, stk1) ([], stk2) ->
    stack_multistep st (p2, stk2) ([], stk3) ->
    stack_multistep st (p1 ++ p2, stk1) ([], stk3).
Proof.
  induction p1; intros; simpl.
  - inversion H; subst.
    + auto.
    + inversion H1.
  - Hint Constructors multi stack_step.
    destruct a;
      find_stackmultistep_invc;
      find_stackstep_invc;
      eapply multi_step;
      eauto;
      eapply IHp1; eauto.
Qed.

Theorem compiler_is_correct' :
  forall (e : aexp) (st : state) (stk : stack),
    stack_multistep st (s_compile e, stk) ([], (aeval st e) :: stk).
Proof.
  induction e; intros; simpl.
  - apply multi_R, SS_Push.
  - apply multi_R, SS_Load.
  - eapply stack_step_app; eauto.
    eapply stack_step_app; eauto.
    apply multi_R, SS_Plus.
  - eapply stack_step_app; eauto.
    eapply stack_step_app; eauto.
    apply multi_R, SS_Minus.
  - eapply stack_step_app; eauto.
    eapply stack_step_app; eauto.
    apply multi_R, SS_Mult.
Qed.

Theorem compiler_is_correct : compiler_is_correct_statement.
Proof.
  unfold compiler_is_correct_statement.
  intros.
  apply compiler_is_correct'.
Qed.

(** [] *)

(* $Date: 2014-04-02 10:55:30 -0400 (Wed, 02 Apr 2014) $ *)


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 A B C Aprime Bprime Cprime O : Universe, ((wd_ B O /\ (wd_ C O /\ (wd_ Bprime O /\ (wd_ Cprime O /\ (wd_ A O /\ (wd_ Aprime O /\ (wd_ A Aprime /\ (wd_ A C /\ (wd_ A B /\ (col_ O A B /\ (col_ O B C /\ (col_ O Aprime Bprime /\ (col_ O Bprime Cprime /\ (col_ O A C /\ (col_ O Aprime Cprime /\ col_ O C Cprime))))))))))))))) -> col_ O A Aprime)).
Proof.
  time tac.
Qed.

End FOFProblem.


Require Import RelationClasses.

From sflib Require Import sflib.

From PromisingLib Require Import Axioms.
From PromisingLib Require Import Basic.
From PromisingLib Require Import DataStructure.
From PromisingLib Require Import DenseOrder.
From PromisingLib Require Import Loc.
From PromisingLib Require Import Event.

Require Import Time.
Require Import View.
Require Import BoolMap.
Require Import Promises.
Require Import Cell.
Require Import Memory.

Set Implicit Arguments.

Module Global.
  Structure t := mk {
    sc: TimeMap.t;
    promises: BoolMap.t;
    memory: Memory.t;
  }.

  Definition init := mk TimeMap.bot BoolMap.bot Memory.init.

  Variant wf (gl: t): Prop :=
  | wf_intro
      (SC_CLOSED: Memory.closed_timemap (sc gl) (memory gl))
      (MEM_CLOSED: Memory.closed (memory gl))
  .
  #[global] Hint Constructors wf: core.

  Lemma init_wf: wf init.
  Proof.
    econs; ss.
    - apply Memory.closed_timemap_bot.
      apply Memory.init_closed.
    - apply Memory.init_closed.
  Qed.

  Definition cap_of (gl: t): t :=
    mk (sc gl) (promises gl) (Memory.cap_of (memory gl)).

  Lemma cap_of_cap gl:
    (<<SC: sc gl = sc (cap_of gl)>>) /\
    (<<GPRM: promises gl = promises (cap_of gl)>>) /\
    (<<MEM: Memory.cap (memory gl) (memory (cap_of gl))>>).
  Proof.
    splits; ss.
    apply Memory.cap_of_cap.
  Qed.

  Lemma cap_wf
        gl
        (WF: wf gl):
    wf (cap_of gl).
  Proof.
    inv WF.
    econs; s; eauto using Memory.cap_of_cap,
      Memory.cap_closed, Memory.cap_closed_timemap.
  Qed.

  Variant future (gl1 gl2: t): Prop :=
  | future_intro
      (SC: TimeMap.le (sc gl1) (sc gl2))
      (MEMORY: Memory.future (memory gl1) (memory gl2))
  .
  #[global] Hint Constructors future: core.

  Global Program Instance future_PreOrder: PreOrder future.
  Next Obligation.
    ii. destruct x. econs; refl.
  Qed.
  Next Obligation.
    ii. destruct x, y, z. inv H. inv H0. ss.
    econs; etrans; eauto.
  Qed.

  Variant le (gl1 gl2: t): Prop :=
    | le_intro
        (SC: TimeMap.le (sc gl1) (sc gl2))
        (MEMORY: Memory.messages_le (memory gl1) (memory gl2))
  .
  #[global] Hint Constructors le: core.

  Global Program Instance le_PreOrder: PreOrder le.
  Next Obligation.
    ii. econs; refl.
  Qed.
  Next Obligation.
    ii. inv H. inv H0. econs; etrans; eauto.
  Qed.

  Lemma future_le
    gl1 gl2
    (FUTURE: future gl1 gl2):
    le gl1 gl2.
  Proof.
    inv FUTURE. econs; ss.
    eauto using Memory.future_messages_le.
  Qed.

  Lemma cap_le
    gl gl_cap
    (CAP: gl_cap = cap_of gl):
    le gl gl_cap.
  Proof.
    destruct gl, gl_cap. inv CAP.
    econs; s; try refl.
    apply Memory.cap_messages_le.
    apply Memory.cap_of_cap.
  Qed.

  Variant na_added_latest (gl1 gl2: t): Prop :=
  | na_added_latest_intro
      (ADDNA: forall loc,
          (<<PROMISES: implb (gl1.(promises) loc) (gl2.(promises) loc)>>) \/
          (<<LATEST: Memory.na_added_latest loc gl1.(memory) gl2.(memory)>>))
  .

  Variant strong_le (gl1 gl2: t): Prop :=
  | strong_le_intro
      (LE: le gl1 gl2)
      (ADDNA: na_added_latest gl1 gl2)
  .
  #[global] Hint Constructors strong_le: core.

  Global Program Instance strong_le_PreOrder: PreOrder strong_le.
  Next Obligation.
    ii. destruct x. econs; [refl|]. econs. i. left. ss. rewrite Bool.implb_same. auto.
  Qed.
  Next Obligation.
    ii. destruct x, y, z. inv H. inv H0. ss. econs.
    { etrans; eauto. }
    { econs. i. ss. destruct (promises0 loc) eqn:PRM0.
      { destruct (promises2 loc) eqn:PRM2.
        { left. ss. }
        destruct (promises1 loc) eqn:PRM1.
        { right. inv ADDNA0. ss. hexploit ADDNA1; eauto.
          rewrite PRM1. rewrite PRM2. i. des; ss.
          eapply Memory.na_added_latest_le.
          { inv LE. eauto. }
          { eauto. }
          { reflexivity. }
        }
        { right. inv ADDNA. ss. hexploit ADDNA1; eauto.
          rewrite PRM0. rewrite PRM1. i. des; ss.
          eapply Memory.na_added_latest_le.
          { reflexivity. }
          { eauto. }
          { inv LE0. eauto. }
        }
      }
      econs; etrans; eauto.
    }
  Qed.

  Lemma cap_strong_le
    gl gl_cap
    (CAP: gl_cap = cap_of gl):
    strong_le gl gl_cap.
  Proof.
    destruct gl, gl_cap. inv CAP. econs.
    { eapply cap_le; eauto. }
    { econs. i. left. ss. rewrite Bool.implb_same. auto. }
  Qed.
End Global.


From Categories Require Import Essentials.Notations.
From Categories Require Import Essentials.Types.
From Categories Require Import Essentials.Facts_Tactics.
From Categories Require Import Category.Main.

From Categories Require Import Basic_Cons.Equalizer.

Section Equalizer_Monic.
  Context {C : Category} {a b} (f g : (a –≻ b)%morphism) {e : Equalizer f g}.

  Program Definition Equalizer_Monic : (e ≫–> a)%morphism :=
    {|
      mono_morphism := equalizer_morph e
    |}.

  Next Obligation. (* mono_morphism_monomorphism *)
  Proof.
    match goal with
        [H : ?A = ?B :> (c –≻ a)%morphism |- _] =>
        let H1 := fresh "H" in
        let H2 := fresh "H" in
        cut (f ∘ A = g ∘ A)%morphism;
          [intros H1;
            cut (f ∘ B = g ∘ B)%morphism;
            [intros H2 | do 2 rewrite <- assoc; rewrite equalizer_morph_com; trivial
          ]| do 2 rewrite <- assoc; rewrite equalizer_morph_com; trivial
          ]
    end.
    eapply equalizer_morph_unique; eauto.
  Qed.

End Equalizer_Monic.


Require Import Iron.Language.SystemF2Cap.Value.Relation.TyJudge.

Lemma typex_kind_type_effect
 :  forall ke te se sp v t e
 ,  TypeX  ke te se sp v t e
 -> (KindT ke sp t KData /\ KindT ke sp e KEffect).
Proof.
 intros. gen ke te se sp t e.
 induction v using exp_mutind with
  (PV := fun v => forall ke te se sp t
      ,  TypeV  ke te se sp v t
      -> KindT  ke sp t KData);
   intros; inverts_type; eauto 1.

 - Case "VBox".
   spec IHv H5. rip.
   eapply KiCon2. simpl. eauto. auto. auto.

 - Case "VLam".
   lets D: IHv H8. rip.
    eapply KiApp.
     unfold AppKind. congruence.
     eapply KiApp.
     unfold AppKind. congruence.
     eapply KiApp.
     unfold AppKind. congruence.
     eapply KiCon0. simpl. eauto.
   auto. auto. auto.

 - Case "VLAM".
   spec IHv H7. rip.

 - Case "XConst".
   destruct c; snorm.

 - Case "XVar".
   burn.

 - Case "XApp".
   lets D1: IHv1 H10.
   lets D2: IHv2 H11.
   rip.

 - Case "XLet".
   lets D1: IHv H6.
   inverts D1.
   inverts H4.
   inverts H8.
   inverts H10.
   simpl in *.
   inverts H5. eauto.

 - Case "XAPP".
   eapply IHv in H6.
   inverts_kind.
   rip.
   eapply subst_type_type; eauto.

 - Case "XOp1".
   destruct o; simpl in *; inverts H6;
    rip.

 - Case "XPrivate".
   spec IHv H11. rip.
   eapply lower_type_type; eauto.
   eapply lower_type_type; eauto.

 - Case "XExtend".
   spec IHv H10. rip.
   + eapply subst_type_type; eauto.
   + eapply KiSum; auto.
     * eapply lower_type_type with (k1 := (OCon, KRegion)).
       eapply H2. eauto.
     * eapply KiCon1; snorm.

 - Case "XRun".
   spec IHv H5. rip.
   inverts_kind.
   + snorm. inverts H4. auto.
   + inverts IHv. snorm. congruence.

 - Case "XAlloc".
   rip.
    eapply KiCon2; eauto. snorm.
    eapply KiCon1; eauto. snorm.

 - Case "XRead".
   rip. spec IHv H9.
   inverts_kind.
   + snorm. inverts H4. auto.
   + eapply KiCon1. simpl. eauto. auto.

 - Case "XWrite".
   rip. eapply KiCon1; eauto. snorm.
Qed.
Hint Resolve typex_kind_type_effect.

Lemma typev_kind_type
 :  forall ke te se sp v t
 ,  TypeV  ke te se sp v t
 -> KindT  ke sp t KData.
Proof.
 intros.
 eapply TxVal in H.
 lets D: typex_kind_type_effect H. rip.
Qed.
Hint Resolve typev_kind_type.

Lemma typex_kind_type
 :  forall ke te se sp x t e
 ,  TypeX  ke te se sp x t e
 -> KindT  ke sp t KData.
Proof.
 intros.
 lets D: typex_kind_type_effect H. rip.
Qed.
Hint Resolve typex_kind_type.

Lemma typex_kind_effect
 :  forall ke te se sp x t e
 ,  TypeX  ke te se sp x t e
 -> KindT  ke sp e KEffect.
Proof.
 intros.
 lets D: typex_kind_type_effect H. rip.
Qed.
Hint Resolve typex_kind_effect.