From Undecidability.L Require Export L Datatypes.LNat Datatypes.LBool Functions.Encoding Computability.Seval.
Require Import Coq.Logic.ConstructiveEpsilon.

Definition cChoice := constructive_indefinite_ground_description_nat_Acc.

Lemma eq_term_dec (s t : term) : (s = t) + (s <> t).
Proof.
  revert t. induction s; intros t; destruct t; try(right; intros H; inv H; fail).
  - decide (n = n0). left. congruence. right. congruence.
  - destruct (IHs1 t1), (IHs2 t2); try (right; congruence). left. congruence.
  - destruct (IHs t). left; congruence. right; congruence.
Qed.

Lemma enc_extinj {X} {R} {H:@encInj X R} (m n:X) : enc m == enc n -> m = n.
Proof.
  intros eq. apply unique_normal_forms in eq; try Lproc. now apply inj_enc.
Qed.

Lemma lcomp_comp Y {Ry:encodable Y} (u:term) (g: term -> Y):
  (forall x (y:Y), enc y = x -> y = g x) ->
  (exists y:Y, u == enc y) -> {y:Y| u == enc y}.
Proof.
  intros Hg Hu.
  assert (exists n (y:Y), eva n u = Some (enc y)).
  {
    destruct Hu as [y Hy]. apply equiv_lambda in Hy;try Lproc.
    assert (eval (u) (enc y)). split. assumption. Lproc.
    apply eval_seval in H. destruct H as [n Hn]. exists n. exists y. now apply seval_eva.
  }
  eapply cChoice in H. destruct H as [n H].
  destruct (eva n u) as [t|] eqn:Heva.
  -exists (g t). destruct H as [y H]. rewrite <- Heva in H. apply eva_equiv in H.
   assert (lambda t)by now apply eva_lam in Heva. apply eva_equiv in Heva. rewrite Heva in H. erewrite <- Hg. apply equiv_lambda in Heva;try Lproc. rewrite Heva. exact H. apply unique_normal_forms in H;try Lproc. congruence.
  -exists (g #0). destruct H as [? H]. inv H.
  -intros n. destruct (eva n u) eqn:eq.
   +left. destruct H as [n' [y H]]. exists y. apply eva_equiv in H.
    assert (lambda t) by now apply eva_lam in eq. apply eva_equiv in eq. rewrite H in eq. apply unique_normal_forms in eq;[|Lproc..].  congruence.
   +right. intros [y eq']. congruence.
Qed.

Definition bool_enc_inv b:=
  match b with
    | lam (lam (var 1)) => true
    | _ => false
  end.

Lemma bool_enc_inv_correct : (forall x (y:bool), enc y = x -> y = bool_enc_inv x).
Proof.
  intros x [];intros;subst;reflexivity.
  Qed.

Arguments lcomp_comp _{_} _ {_} _ _.


Require Export SystemFR.Judgments.
Require Export SystemFR.AnnotatedTactics.
Require Export SystemFR.ErasedTypeRefine.

Lemma annotated_reducible_type_refine:
  forall Θ Γ A B t1 t2,
    wf B 1 ->
    is_annotated_type B ->
    is_annotated_term t1 ->
    subset (fv B) (support Γ) ->
    [[ Θ; Γ ⊨ t1 : A ]] ->
    [[ Θ; Γ ⊨ t2 : open 0 B t1 ]] ->
    [[ Θ; Γ ⊨ because t1 t2 : T_type_refine A B ]].
Proof.
  intros.
  eapply open_reducible_type_refine; try eassumption;
    repeat step || erase_open;
    side_conditions.
Qed.

Lemma annotated_reducible_get_refinement_witness:
  forall Θ Γ t1 t2 A B T x,
    ~(x ∈ Θ) ->
    ~(x ∈ fv_context Γ) ->
    ~(x ∈ fv t1) ->
    ~(x ∈ fv t2) ->
    ~(x ∈ fv T) ->
    ~(x ∈ fv A) ->
    ~(x ∈ fv B) ->
    wf t1 0 ->
    wf (erase_term t2) 0 ->
    wf B 1 ->
    subset (fv t1) (support Γ) ->
    subset (fv t2) (support Γ) ->
    subset (fv B) (support Γ) ->
    is_annotated_type B ->
    is_annotated_term t1 ->
    is_annotated_term t2 ->
    [[ Θ; Γ ⊨ t1 : T_type_refine A B ]] ->
    [[ Θ; (x, open 0 B t1) :: Γ ⊨ open 0 t2 (fvar x term_var) : T ]] ->
    [[ Θ; Γ ⊨ get_refinement_witness t1 t2 : T ]].
Proof.
  intros.
  apply open_reducible_get_refinement_witness
    with (erase_term t1) (erase_type A) (erase_type B) x; try eassumption;
    repeat step || erase_open || rewrite (open_none (erase_term t2)) in * by auto;
    side_conditions.
Qed.


(** * A strong characterization of the type constructor [A] *)

Require Import Coq.Logic.Decidable.
Require Import Coq.Program.Basics.
Require Import Coq.Program.Equality.
Require Import Coq.Setoids.Setoid.
Require Import Coq.Classes.RelationClasses.
Require Import Coq.Classes.Morphisms.
Require Export TypeConstructor.
Require Import Nontermination.
Require Import LeastFixedPoint.
Require Import BohmTrees.
Open Scope code_scope.

(* ------------------------------------------------------------------------ *)
(** ** An implicit definition of [A] *)

Definition is_pair {Var : Set} (x : Code Var) := x == [x * K, x * (K * I)].
Lemma pair_is_pair (Var : Set) (x y : Code Var) : is_pair [x, y].
Proof.
  hnf; unfold pair; beta_reduce; auto.
Qed.

Definition sub_pair {Var : Set} (x : Code Var) := x [= [TOP, TOP].

Instance sub_pair_eq (Var : Set) :
  Proper (code_eq ==> iff) (@sub_pair Var).
Proof.
  unfold sub_pair; intros x x' xx'; split; rewrite xx'; auto.
Qed.

Instance sub_pair_le (Var : Set) :
  Proper (code_le --> impl) (@sub_pair Var).
Proof.
  unfold sub_pair; intros x x' xx' H. rewrite <- xx'; auto.
Qed.

Lemma sub_pair_pair (Var : Set) (x y : Code Var) : sub_pair [x, y].
Proof.
  unfold sub_pair, pair; eta_expand as f; beta_reduce.
  monotonicity; auto.
Qed.

(* FIXME is this true? *)
Lemma sub_pair_elim_intro (Var : Set) (x : Code Var) :
  sub_pair x -> x [= [x*K, x*(K*I)].
Proof.
  unfold sub_pair, pair; simpl.
  intros H. (* eta_expand in H. FIXME eta_expand is borken *)
  eta_expand as f; beta_reduce.
Admitted.

Definition pairish {Var : Set} (x : Code Var) :=
  [BOT, BOT] [= x /\ x [= [TOP, TOP].

(* FIXME is this true? what about for stochastic terms? *)
Lemma pairish_elim (Var : Set) (x f y : Code Var) :
  pairish x ->
  (forall s r, [s, r] [= x -> f * s * r [= y) ->
  x * f [= y.
Proof.
Admitted.

(* should we work only in the lattice inverval [[<BOT,BOT>, <TOP, TOP>]]? *)
Definition A_prop' {Var : Set} (a : Code Var) :=
  [BOT, BOT] [= a /\
  a [= [TOP, TOP] /\
  forall s r, [s, r] [= a -> r o s [= I.

Definition A_prop {Var : Set} (a : Code Var) :=
  sub_pair a /\ forall s r, [s, r] [= a -> r o s [= I.

Instance A_prop_le (Var : Set) : Proper (code_le --> impl) (@A_prop Var).
Proof.
  unfold A_prop; intros x x' xx'; intros [Hs Hl]; split.
     rewrite <- xx'; auto.
  intros s r H; rewrite <- xx' in *; auto.
Qed.

Instance A_prop_eq (Var : Set) : Proper (code_eq ==> iff) (@A_prop Var).
Proof.
  split; destruct H as [Hl Hr]; apply A_prop_le; auto.
Qed.

Ltac A_prop_pair :=
  unfold A_prop; unfold sub_pair; split;
  [ try apply pair_extensionality; auto
  | intros s r H;
    apply pair_extensionality in H;
    destruct H as [Hs Hr];
    rewrite Hs; rewrite Hr
  ].

(* ------------------------------------------------------------------------ *)
(** ** An inductive definition of [A] *)

Lemma A_I_I (Var : Set) : A_prop ([I, I] : Code Var).
Proof.
  A_prop_pair; beta_eta.
Qed.
Hint Resolve A_I_I.

Lemma A_raise_lower (Var : Set) : (@A_prop Var) [raise, lower].
Proof.
  A_prop_pair; eta_expand; beta_simpl; apply lower_raise.
Qed.

Lemma A_pull_push (Var : Set) : (@A_prop Var) [pull, push].
Proof.
  A_prop_pair; eta_expand; beta_simpl; apply push_pull.
Qed.
Hint Resolve A_raise_lower.
Hint Resolve A_pull_push.

Lemma A_compose (Var : Set) (a : Code Var) : A_prop a -> A_prop (compose * a).
Proof.
  unfold A_prop, sub_pair; intros [Hs Ha]; split.
Admitted.
Hint Resolve A_compose.

Lemma A_conjugate (Var : Set) (a : Code Var) :
  A_prop a -> A_prop (conjugate * a).
Proof.
  unfold A_prop, sub_pair; intros [Hs Ha]; split.
Admitted.
Hint Resolve A_conjugate.

(* OLD
Lemma A_compose : forall a, A_prop a -> A_prop (compose * a).
Proof.
  intros a H.
  unfold A_prop in H; destruct H as [Hpair Hless].
  unfold is_pair in Hpair.
  rewrite Hpair.
  unfold A_prop; split.
    compute; beta_reduce; auto.
  compute; eta_expand; beta_reduce.
  transitivity (a * (K*I) * (a * K * H));
    monotonicity; eta_expand in Hless; apply Hless.
Qed.

Lemma A_conjugate : forall a, A_prop a -> A_prop (conjugate * a).
Proof.
  intros a H.
  unfold A_prop in H; destruct H as [Hpair Hless].
  unfold is_pair in Hpair.
  rewrite Hpair.
  unfold A_prop; split.
    compute; beta_reduce; auto.
  compute; eta_expand; eta_expand; beta_reduce.
  transitivity (a * (K*I) * (a * K * (H * H0)));
    monotonicity; eta_expand in Hless; apply Hless.
Qed.
*)

Inductive A_above {Var : Set} : Code Var -> Prop :=
  | A_above_below x y : x [= y -> A_above y -> A_above x
  | A_above_i_i : A_above [I, I]
  | A_above_raise_lower : A_above [raise, lower]
  | A_above_pull_push : A_above [pull, push]
  | A_above_compose a : A_above a -> A_above (compose * a)
  | A_above_conjugate a : A_above a -> A_above (conjugate * a).
Hint Constructors A_above.

Instance A_above_le (Var : Set) : Proper (code_le --> impl) (@A_above Var).
Proof.
  intros x x' xx' H; apply A_above_below with x; auto.
Qed.

Instance A_above_eq (Var : Set) : Proper (code_eq ==> iff) (@A_above Var).
Proof.
  split; destruct H as [Hl Hr]; apply A_above_le; auto.
Qed.

Lemma A_above_sound (Var : Set) (sr : Code Var) : A_above sr -> A_prop sr.
Proof.
  intro H; induction H; auto.
  rewrite H; auto.
Qed.

(** The main lemma *)

Lemma A_above_complete (Var : Set) (sr : Code Var) : A_prop sr -> A_above sr.
Proof.
  intro H; destruct H as [Hp Hl].
Admitted.

(* ------------------------------------------------------------------------ *)
(** ** A constructive definition of [A] *)

Lemma A_complete (Var : Set) (sr : Code Var) : A_prop sr -> sr [= A.
Proof.
  A_simpl.
  intros H; apply A_above_complete in H.
  induction H; auto.
  - transitivity y; auto.
  - rewrite pi_j_left, pi_j_left, pi_j_left, code_eq_y; beta_simpl; auto.
  - rewrite pi_j_left, pi_j_left, pi_j_right, code_eq_y; beta_simpl; auto.
  - rewrite pi_j_left, pi_j_right, code_eq_y; beta_simpl; auto.
  - rewrite code_eq_y; beta_simpl;
    rewrite pi_j_right, pi_j_left, IHA_above; auto.
  - rewrite code_eq_y; beta_simpl;
    rewrite pi_j_right, pi_j_right, IHA_above; auto.
Qed.

Lemma A_sound (Var : Set) (s r : Code Var) : [s, r] [= A -> A_prop [s, r].
Proof.
  A_simpl.
  intros H; apply A_above_sound.
  (* TODO reason about pairs and least fixed points *)
Admitted.


(** * Hoare: Hoare Logic, Part I *)
Add LoadPath "F:\Dropbox\ITU\SDT\PLS\exercises\assignment_07".
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.EqNat.
Require Import Coq.omega.Omega.
Require Import Imp.
Require Import Maps.
(* /TERSE: HIDEFROMHTML *)

(** In the past couple of chapters, we've begun applying the
    mathematical tools developed in the first part of the course to
    studying the theory of a small programming language, Imp.

    - We defined a type of _abstract syntax trees_ for Imp, together
      with an _evaluation relation_ (a partial function on states)
      that specifies the _operational semantics_ of programs.

      The language we defined, though small, captures some of the key
      features of full-blown languages like C, C++, and Java,
      including the fundamental notion of mutable state and some
      common control structures.

    - We proved a number of _metatheoretic properties_ -- "meta" in
      the sense that they are properties of the language as a whole,
      rather than of particular programs in the language.  These
      included:

        - determinism of evaluation

        - equivalence of some different ways of writing down the
          definitions (e.g., functional and relational definitions of
          arithmetic expression evaluation)

        - guaranteed termination of certain classes of programs

        - correctness (in the sense of preserving meaning) of a number
          of useful program transformations

        - behavioral equivalence of programs (in the [Equiv] chapter).

    If we stopped here, we would already have something useful: a set
    of tools for defining and discussing programming languages and
    language features that are mathematically precise, flexible, and
    easy to work with, applied to a set of key properties.  All of
    these properties are things that language designers, compiler
    writers, and users might care about knowing.  Indeed, many of them
    are so fundamental to our understanding of the programming
    languages we deal with that we might not consciously recognize
    them as "theorems."  But properties that seem intuitively obvious
    can sometimes be quite subtle (sometimes also subtly wrong!).

    We'll return to the theme of metatheoretic properties of whole
    languages later in the book when we discuss _types_ and _type
    soundness_.  In this chapter, though, we turn to a different set
    of issues.

    Our goal is to carry out some simple examples of _program
    verification_ -- i.e., to use the precise definition of Imp to
    prove formally that particular programs satisfy particular
    specifications of their behavior.  We'll develop a reasoning
    system called _Floyd-Hoare Logic_ -- often shortened to just
    _Hoare Logic_ -- in which each of the syntactic constructs of Imp
    is equipped with a generic "proof rule" that can be used to reason
    compositionally about the correctness of programs involving this
    construct.

    Hoare Logic originated in the 1960s, and it continues to be the
    subject of intensive research right up to the present day.  It
    lies at the core of a multitude of tools that are being used in
    academia and industry to specify and verify real software
    systems.

    Hoare Logic combines two beautiful ideas: a natural way of
    writing down _specifications_ of programs, and a _compositional
    proof technique_ for proving that programs are correct with
    respect to such specifications -- where by "compositional" we mean
    that the structure of proofs directly mirrors the structure of the
    programs that they are about. *)

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

(** To talk about specifications of programs, the first thing we
    need is a way of making _assertions_ about properties that hold at
    particular points during a program's execution -- i.e., claims
    about the current state of the memory when execution reaches that
    point.  Formally, an assertion is just a family of propositions
    indexed by a [state]. *)

Definition Assertion := state -> Prop.

(** **** Exercise: 1 star, optional (assertions)  *)
(** Paraphrase the following assertions in English (or your favorite
    natural language). *)

Module ExAssertions.
Definition as1 : Assertion := fun st => st X = 3.
Definition as2 : Assertion := fun st => st X <= st Y.
Definition as3 : Assertion :=
  fun st => st X = 3 \/ st X <= st Y.
Definition as4 : Assertion :=
  fun st => st Z * st Z <= st X /\
            ~ (((S (st Z)) * (S (st Z))) <= st X).
Definition as5 : Assertion := fun st => True.
Definition as6 : Assertion := fun st => False.
(* FILL IN HERE *)
End ExAssertions.
(** [] *)

(** This way of writing assertions can be a little bit heavy,
    for two reasons: (1) every single assertion that we ever write is
    going to begin with [fun st => ]; and (2) this state [st] is the
    only one that we ever use to look up variables in assertions (we
    will never need to talk about two different memory states at the
    same time).  For discussing examples informally, we'll adopt some
    simplifying conventions: we'll drop the initial [fun st =>], and
    we'll write just [X] to mean [st X].  Thus, instead of writing *)
(**

      fun st => (st Z) * (st Z) <= m /\
                ~ ((S (st Z)) * (S (st Z)) <= m)

    we'll write just

      Z * Z <= m /\ ~((S Z) * (S Z) <= m).
*)

(** Given two assertions [P] and [Q], we say that [P] _implies_ [Q],
    written [P ->> Q] (in ASCII, [P -][>][> Q]), if, whenever [P]
    holds in some state [st], [Q] also holds. *)

Definition assert_implies (P Q : Assertion) : Prop :=
  forall st, P st -> Q st.

Notation "P ->> Q" := (assert_implies P Q)
                      (at level 80) : hoare_spec_scope.
Open Scope hoare_spec_scope.

(** (The [hoare_spec_scope] annotation here tells Coq that this
    notation is not global but is intended to be used in particular
    contexts.  The [Open Scope] tells Coq that this file is one such
    context.) *)

(** We'll also want the "iff" variant of implication between
    assertions: *)

Notation "P <<->> Q" :=
  (P ->> Q /\ Q ->> P) (at level 80) : hoare_spec_scope.

(* ################################################################# *)
(** * Hoare Triples *)

(** Next, we need a way of making formal claims about the
    behavior of commands. *)

(** In general, the behavior of a command is to transform one state to
    another, so it is natural to express claims about commands in
    terms of assertions that are true before and after the command
    executes:

      - "If command [c] is started in a state satisfying assertion
        [P], and if [c] eventually terminates in some final state,
        then this final state will satisfy the assertion [Q]."

    Such a claim is called a _Hoare Triple_.  The property [P] is
    called the _precondition_ of [c], while [Q] is the
    _postcondition_.  Formally: *)

Definition hoare_triple
           (P:Assertion) (c:com) (Q:Assertion) : Prop :=
  forall st st',
     c / st \\ st'  ->
     P st  ->
     Q st'.

(** Since we'll be working a lot with Hoare triples, it's useful to
    have a compact notation:

       {{P}} c {{Q}}.
*)
(** (The traditional notation is [{P} c {Q}], but single braces
    are already used for other things in Coq.)  *)

Notation "{{ P }}  c  {{ Q }}" :=
  (hoare_triple P c Q) (at level 90, c at next level)
  : hoare_spec_scope.

(** **** Exercise: 1 star, optional (triples)  *)
(** Paraphrase the following Hoare triples in English.

   1) {{True}} c {{X = 5}}

   2) {{X = m}} c {{X = m + 5)}}

   3) {{X <= Y}} c {{Y <= X}}

   4) {{True}} c {{False}}

   5) {{X = m}}
      c
      {{Y = real_fact m}}

   6) {{True}}
      c
      {{(Z * Z) <= m /\ ~ (((S Z) * (S Z)) <= m)}}
*)

(** [] *)

(** **** Exercise: 1 star, optional (valid_triples)  *)
(** Which of the following Hoare triples are _valid_ -- i.e., the
    claimed relation between [P], [c], and [Q] is true?

   1) {{True}} X ::= 5 {{X = 5}} valid

   2) {{X = 2}} X ::= X + 1 {{X = 3}} valid

   3) {{True}} X ::= 5; Y ::= 0 {{X = 5}} valid

   4) {{X = 2 /\ X = 3}} X ::= 5 {{X = 0}} valid (absurd)

   5) {{True}} SKIP {{False}} invalid

   6) {{False}} SKIP {{True}} valid (absurd)

   7) {{True}} WHILE True DO SKIP END {{False}} valid (absurd)

   8) {{X = 0}}
      WHILE X == 0 DO X ::= X + 1 END
      {{X = 1}} valid

   9) {{X = 1}}
      WHILE X <> 0 DO X ::= X + 1 END
      {{X = 100}} valid (absurd)
*)
(** [] *)

(** (Note that we're using informal mathematical notations for
   expressions inside of commands, for readability, rather than their
   formal [aexp] and [bexp] encodings.  We'll continue doing so
   throughout the chapter.)

   To get us warmed up for what's coming, here are two simple
   facts about Hoare triples. *)

Theorem hoare_post_true : forall (P Q : Assertion) c,
  (forall st, Q st) ->
  {{P}} c {{Q}}.
Proof.
  intros P Q c H st st' H0 H1. apply H.
Qed.

Theorem hoare_pre_false : forall (P Q : Assertion) c,
  (forall st, ~(P st)) ->
  {{P}} c {{Q}}.
Proof.
  intros P Q c H st st' H0 H1. unfold "~" in H. contradiction (H st H1).
Qed.

(* ################################################################# *)
(** * Proof Rules *)

(** The goal of Hoare logic is to provide a _compositional_
    method for proving the validity of specific Hoare triples.  That
    is, we want the structure of a program's correctness proof to
    mirror the structure of the program itself.  To this end, in the
    sections below, we'll introduce a rule for reasoning about each of
    the different syntactic forms of commands in Imp -- one for
    assignment, one for sequencing, one for conditionals, etc. -- plus
    a couple of "structural" rules for gluing things together.  We
    will then be able to prove programs correct using these proof
    rules, without ever unfolding the definition of [hoare_triple]. *)

(* ================================================================= *)
(** ** Assignment *)

(** The rule for assignment is the most fundamental of the Hoare logic
    proof rules.  Here's how it works.

    Consider this valid Hoare triple:

       {{ Y = 1 }}  X ::= Y  {{ X = 1 }}

    In English: if we start out in a state where the value of [Y]
    is [1] and we assign [Y] to [X], then we'll finish in a
    state where [X] is [1].  That is, the property of being equal
    to [1] gets transferred from [Y] to [X].

    Similarly, in

       {{ Y + Z = 1 }}  X ::= Y + Z  {{ X = 1 }}

    the same property (being equal to one) gets transferred to
    [X] from the expression [Y + Z] on the right-hand side of
    the assignment.

    More generally, if [a] is _any_ arithmetic expression, then

       {{ a = 1 }}  X ::= a {{ X = 1 }}

    is a valid Hoare triple.

    This can be made even more general. To conclude that an
    arbitrary property [Q] holds after [X ::= a], we need to assume
    that [Q] holds before [X ::= a], but _with all occurrences of_ [X]
    replaced by [a] in [Q]. This leads to the Hoare rule for
    assignment

      {{ Q [X |-> a] }} X ::= a {{ Q }}

    where "[Q [X |-> a]]" is pronounced "[Q] where [a] is substituted
    for [X]".

    For example, these are valid applications of the assignment
    rule:

      {{ (X <= 5) [X |-> X + 1]
         i.e., X + 1 <= 5 }}
      X ::= X + 1
      {{ X <= 5 }}

      {{ (X = 3) [X |-> 3]
         i.e., 3 = 3}}
      X ::= 3
      {{ X = 3 }}

      {{ (0 <= X /\ X <= 5) [X |-> 3]
         i.e., (0 <= 3 /\ 3 <= 5)}}
      X ::= 3
      {{ 0 <= X /\ X <= 5 }}
*)

(** To formalize the rule, we must first formalize the idea of
    "substituting an expression for an Imp variable in an assertion."
    That is, given a proposition [P], a variable [X], and an
    arithmetic expression [a], we want to derive another proposition
    [P'] that is just the same as [P] except that, wherever [P]
    mentions [X], [P'] should instead mention [a].

    Since [P] is an arbitrary Coq proposition, we can't directly
    "edit" its text.  Instead, we can achieve the effect we want by
    evaluating [P] in an updated state: *)

Definition assn_sub X a P : Assertion :=
  fun (st : state) =>
    P (t_update st X (aeval st a)).

Notation "P [ X |-> a ]" := (assn_sub X a P) (at level 10).

(** That is, [P [X |-> a]] is an assertion -- let's call it [P'] --
    that is just like [P] except that, wherever [P] looks up the
    variable [X] in the current state, [P'] instead uses the value
    of the expression [a].

    To see how this works, let's calculate what happens with a couple
    of examples.  First, suppose [P'] is [(X <= 5) [X |-> 3]] -- that
    is, more formally, [P'] is the Coq expression

    fun st =>
      (fun st' => st' X <= 5)
      (t_update st X (aeval st (ANum 3))),

    which simplifies to

    fun st =>
      (fun st' => st' X <= 5)
      (t_update st X 3)

    and further simplifies to

    fun st =>
      ((t_update st X 3) X) <= 5)

    and by further simplification to

    fun st =>
      (3 <= 5).

    That is, [P'] is the assertion that [3] is less than or equal to
    [5] (as expected).

    For a more interesting example, suppose [P'] is [(X <= 5) [X |->
    X+1]].  Formally, [P'] is the Coq expression

    fun st =>
      (fun st' => st' X <= 5)
      (t_update st X (aeval st (APlus (AId X) (ANum 1)))),

    which simplifies to

    fun st =>
      (((t_update st X (aeval st (APlus (AId X) (ANum 1))))) X) <= 5

    and further simplifies to

    fun st =>
      (aeval st (APlus (AId X) (ANum 1))) <= 5.

    That is, [P'] is the assertion that [X+1] is at most [5].
*)

(** Now we can give the precise proof rule for assignment:

      ------------------------------ (hoare_asgn)
      {{Q [X |-> a]}} X ::= a {{Q}}
*)

(** We can prove formally that this rule is indeed valid. *)

Theorem hoare_asgn : forall Q X a,
  {{Q [X |-> a]}} (X ::= a) {{Q}}.
Proof.
  intros Q X a st st' H1 H2.
  unfold assn_sub in H2. inversion H1. subst.
  apply H2.
Qed.

(** Here's a first formal proof using this rule. *)

Example assn_sub_example :
  {{(fun st => st X = 3) [X |-> ANum 3]}}
  (X ::= (ANum 3))
  {{fun st => st X = 3}}.
Proof.
  apply hoare_asgn.  Qed.

(** **** Exercise: 2 stars (hoare_asgn_examples)  *)
(** Translate these informal Hoare triples...

    1) {{ (X <= 5) [X |-> X + 1] }}
       X ::= X + 1
       {{ X <= 5 }}

    2) {{ (0 <= X /\ X <= 5) [X |-> 3] }}
       X ::= 3
       {{ 0 <= X /\ X <= 5 }}

   ...into formal statements (use the names [assn_sub_ex1]
   and [assn_sub_ex2]) and use [hoare_asgn] to prove them. *)

Example assn_sub_ex1 :
  {{(fun st => st X <= 5) [X |-> APlus (AId X) (ANum 1)]}}
  (X ::= APlus (AId X) (ANum 1))
  {{(fun st => st X <= 5)}}.
Proof. apply hoare_asgn. Qed.

Example assn_sub_ex2 :
  {{(fun st => 0 <= st X /\ st X <= 5) [X |-> ANum 3]}}
  (X ::= (ANum 3))
  {{(fun st => 0 <= st X /\ st X <= 5)}}.
Proof. apply hoare_asgn. Qed.
(** [] *)

(** **** Exercise: 2 stars (hoare_asgn_wrong)  *)
(** The assignment rule looks backward to almost everyone the first
    time they see it.  If it still seems puzzling, it may help
    to think a little about alternative "forward" rules.  Here is a
    seemingly natural one:

      ------------------------------ (hoare_asgn_wrong)
      {{ True }} X ::= a {{ X = a }}

    Give a counterexample showing that this rule is incorrect and
    argue informally that it is really a counterexample.  (Hint:
    The rule universally quantifies over the arithmetic expression
    [a], and your counterexample needs to exhibit an [a] for which
    the rule doesn't work.) *)

(**
what if a = Plus (AId X) (ANum 1), then the postcondition will say that
X = X + 1 which is a recursive equation with no solution.
**)

Theorem hoare_asgn_wrong : (forall X a,
  {{fun _ => True}} (X ::= a) {{fun st => st X = (aeval st a)}}) -> False.
Proof.
  intros H. unfold hoare_triple in H.
  remember (t_update empty_state X 5) as st.
  remember (t_update st X 6) as st'.
  remember (APlus (AId X) (ANum 1)) as a.
  specialize (H X a st st').
  subst. simpl in H.
  rewrite t_update_eq in H. assert (6 = 7 -> False) by omega.
  apply H0. apply H.
  * constructor. reflexivity.
  * apply I.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (hoare_asgn_fwd)  *)
(** However, by using an auxiliary variable [m] to remember the
    original value of [X] we can define a Hoare rule for assignment
    that does, intuitively, "work forwards" rather than backwards.

       ------------------------------------------ (hoare_asgn_fwd)
       {{fun st => P st /\ st X = m}}
         X ::= a
       {{fun st => P st' /\ st X = aeval st' a }}
       (where st' = t_update st X m)

    Note that we use the original value of [X] to reconstruct the
    state [st'] before the assignment took place. Prove that this rule
    is correct (the first hypothesis is the functional extensionality
    axiom, which you will need at some point). Also note that this
    rule is more complicated than [hoare_asgn].
*)

Theorem hoare_asgn_fwd :
  (forall {X Y: Type} {f g : X -> Y},
     (forall (x: X), f x = g x) ->  f = g) ->
  forall m a P,
  {{fun st => P st /\ st X = m}}
    X ::= a
  {{fun st => P (t_update st X m)
            /\ st X = aeval (t_update st X m) a }}.
Proof.
  intros functional_extensionality m a P.
  unfold hoare_triple. intros. destruct H0.
  split.
  - assert (st = t_update st' X m). apply functional_extensionality.
    + intros. unfold t_update. destruct (beq_id X x) eqn:Hbeq.
      * rewrite beq_id_true_iff in Hbeq. subst. reflexivity.
      * inversion H. unfold t_update. destruct (beq_id X x); [| omega ].
        subst. inversion Hbeq.
    + rewrite <- H2. assumption.
  - inversion H. subst.  rewrite t_update_shadow. rewrite t_update_same. reflexivity.
Qed.

(** [] *)

(** **** Exercise: 2 stars, advanced (hoare_asgn_fwd_exists)  *)
(** Another way to define a forward rule for assignment is to
    existentially quantify over the previous value of the assigned
    variable.

      ------------------------------------ (hoare_asgn_fwd_exists)
      {{fun st => P st}}
        X ::= a
      {{fun st => exists m, P (t_update st X m) /\
                     st X = aeval (t_update st X m) a }}
*)

Theorem hoare_asgn_fwd_exists :
  (forall {X Y: Type} {f g : X -> Y},
     (forall (x: X), f x = g x) ->  f = g) ->
  forall a P,
  {{fun st => P st}}
    X ::= a
  {{fun st => exists m, P (t_update st X m) /\
                st X = aeval (t_update st X m) a }}.
Proof.
  intros functional_extensionality a P.
  unfold hoare_triple. intros.
  exists (st X). split.
  - assert (st = t_update st' X (st X)). apply functional_extensionality. intros.
    + unfold t_update. destruct (beq_id X x) eqn:Heq.
      * rewrite beq_id_true_iff in Heq. rewrite Heq. reflexivity.
      * inversion H. subst. unfold t_update. rewrite Heq. reflexivity.
    + rewrite <- H1. assumption.
  - inversion H. subst. rewrite t_update_shadow. rewrite t_update_same. reflexivity.
Qed.

(** [] *)

(* ================================================================= *)
(** ** Consequence *)

(** Sometimes the preconditions and postconditions we get from the
    Hoare rules won't quite be the ones we want in the particular
    situation at hand -- they may be logically equivalent but have a
    different syntactic form that fails to unify with the goal we are
    trying to prove, or they actually may be logically weaker (for
    preconditions) or stronger (for postconditions) than what we need.
    For instance, while

      {{(X = 3) [X |-> 3]}} X ::= 3 {{X = 3}},

    follows directly from the assignment rule,

      {{True}} X ::= 3 {{X = 3}}

    does not.  This triple is valid, but it is not an instance of
    [hoare_asgn] because [True] and [(X = 3) [X |-> 3]] are not
    syntactically equal assertions.  However, they are logically
    equivalent, so if one triple is valid, then the other must
    certainly be as well.  We can capture this observation with the
    following rule:

                {{P'}} c {{Q}}
                  P <<->> P'
         -----------------------------   (hoare_consequence_pre_equiv)
                {{P}} c {{Q}}

    Taking this line of thought a bit further, we can see that
    strengthening the precondition or weakening the postcondition of a
    valid triple always produces another valid triple. This
    observation is captured by two _Rules of Consequence_.

                {{P'}} c {{Q}}
                   P ->> P'
         -----------------------------   (hoare_consequence_pre)
                {{P}} c {{Q}}

                {{P}} c {{Q'}}
                  Q' ->> Q
         -----------------------------    (hoare_consequence_post)
                {{P}} c {{Q}}
*)

(** Here are the formal versions: *)

Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c,
  {{P'}} c {{Q}} ->
  P ->> P' ->
  {{P}} c {{Q}}.
Proof.
  intros P P' Q c H H0 st st' H1 H2.
  apply (H st st' H1). apply (H0 _ H2).
Qed.

Theorem hoare_consequence_post : forall (P Q Q' : Assertion) c,
  {{P}} c {{Q'}} ->
  Q' ->> Q ->
  {{P}} c {{Q}}.
Proof.
  intros P Q Q' c H1 H2 st st' H3 H4.
  apply H2. apply (H1 st st' H3 H4).
Qed.

(** For example, we can use the first consequence rule like this:

                {{ True }} ->>
                {{ 1 = 1 }}
    X ::= 1
                {{ X = 1 }}

    Or, formally... *)

Example hoare_asgn_example1 :
  {{fun st => True}} (X ::= (ANum 1)) {{fun st => st X = 1}}.
Proof.
  apply hoare_consequence_pre
    with (P' := (fun st => st X = 1) [X |-> ANum 1]).
  apply hoare_asgn.
  intros st H. unfold assn_sub, t_update. simpl. reflexivity.
Qed.

(** Finally, for convenience in some proofs, we can state a combined
    rule of consequence that allows us to vary both the precondition
    and the postcondition at the same time.

                {{P'}} c {{Q'}}
                   P ->> P'
                   Q' ->> Q
         -----------------------------   (hoare_consequence)
                {{P}} c {{Q}}
*)

Theorem hoare_consequence : forall (P P' Q Q' : Assertion) c,
  {{P'}} c {{Q'}} ->
  P ->> P' ->
  Q' ->> Q ->
  {{P}} c {{Q}}.
Proof.
  intros P P' Q Q' c Hht HPP' HQ'Q.
  apply hoare_consequence_pre with (P' := P').
  apply hoare_consequence_post with (Q' := Q').
  assumption. assumption. assumption.  Qed.

(* ================================================================= *)
(** ** Digression: The [eapply] Tactic *)

(** This is a good moment to introduce another convenient feature of
    Coq.  We had to write "[with (P' := ...)]" explicitly in the proof
    of [hoare_asgn_example1] and [hoare_consequence] above, to make
    sure that all of the metavariables in the premises to the
    [hoare_consequence_pre] rule would be set to specific
    values.  (Since [P'] doesn't appear in the conclusion of
    [hoare_consequence_pre], the process of unifying the conclusion
    with the current goal doesn't constrain [P'] to a specific
    assertion.)

    This is annoying, both because the assertion is a bit long and
    also because, in [hoare_asgn_example1], the very next thing we are
    going to do -- applying the [hoare_asgn] rule -- will tell us
    exactly what it should be!  We can use [eapply] instead of [apply]
    to tell Coq, essentially, "Be patient: The missing part is going
    to be filled in later in the proof." *)

Example hoare_asgn_example1' :
  {{fun st => True}}
  (X ::= (ANum 1))
  {{fun st => st X = 1}}.
Proof.
  eapply hoare_consequence_pre.
  apply hoare_asgn.
  intros st H.  reflexivity.  Qed.

(** In general, [eapply H] tactic works just like [apply H] except
    that, instead of failing if unifying the goal with the conclusion
    of [H] does not determine how to instantiate all of the variables
    appearing in the premises of [H], [eapply H] will replace these
    variables with _existential variables_ (written [?nnn]), which
    function as placeholders for expressions that will be
    determined (by further unification) later in the proof. *)

(** In order for [Qed] to succeed, all existential variables need to
    be determined by the end of the proof. Otherwise Coq
    will (rightly) refuse to accept the proof. Remember that the Coq
    tactics build proof objects, and proof objects containing
    existential variables are not complete. *)

Lemma silly1 : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
  (forall x y : nat, P x y) ->
  (forall x y : nat, P x y -> Q x) ->
  Q 42.
Proof.
  intros P Q HP HQ. eapply HQ. apply HP.

(** Coq gives a warning after [apply HP].  (The warnings look
    different between Coq 8.4 and Coq 8.5.  In 8.4, the warning says
    "No more subgoals but non-instantiated existential variables."  In
    8.5, it says "All the remaining goals are on the shelf," meaning
    that we've finished all our top-level proof obligations but along
    the way we've put some aside to be done later, and we have not
    finished those.)  Trying to close the proof with [Qed] gives an
    error. *)

Abort.

(** An additional constraint is that existential variables cannot be
    instantiated with terms containing ordinary variables that did not
    exist at the time the existential variable was created.  (The
    reason for this technical restriction is that allowing such
    instantiation would lead to inconsistency of Coq's logic.) *)

Lemma silly2 :
  forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
  (exists y, P 42 y) ->
  (forall x y : nat, P x y -> Q x) ->
  Q 42.
Proof.
  intros P Q HP HQ. eapply HQ. destruct HP as [y HP'].

(** Doing [apply HP'] above fails with the following error:

     Error: Impossible to unify "?175" with "y".

    In this case there is an easy fix: doing [destruct HP] _before_
    doing [eapply HQ]. *)

Abort.

Lemma silly2_fixed :
  forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
  (exists y, P 42 y) ->
  (forall x y : nat, P x y -> Q x) ->
  Q 42.
Proof.
  intros P Q HP HQ. destruct HP as [y HP'].
  eapply HQ. apply HP'.
Qed.

(** The [apply HP'] in the last step unifies the existential variable
    in the goal with the variable [y].

    Note that the [assumption] tactic doesn't work in this case, since
    it cannot handle existential variables.  However, Coq also
    provides an [eassumption] tactic that solves the goal if one of
    the premises matches the goal up to instantiations of existential
    variables. We can use it instead of [apply HP'] if we like. *)

Lemma silly2_eassumption : forall (P : nat -> nat -> Prop) (Q : nat -> Prop),
  (exists y, P 42 y) ->
  (forall x y : nat, P x y -> Q x) ->
  Q 42.
Proof.
  intros P Q HP HQ. destruct HP as [y HP']. eapply HQ. eassumption.
Qed.

(** **** Exercise: 2 stars (hoare_asgn_examples_2)  *)
(** Translate these informal Hoare triples...

       {{ X + 1 <= 5 }}  X ::= X + 1  {{ X <= 5 }}
       {{ 0 <= 3 /\ 3 <= 5 }}  X ::= 3  {{ 0 <= X /\ X <= 5 }}

   ...into formal statements (name them [assn_sub_ex1'] and
   [assn_sub_ex2']) and use [hoare_asgn] and [hoare_consequence_pre]
   to prove them. *)

Example ass_sub_ex1' :
  {{fun st =>  st X + 1 <= 5 }}  X ::= APlus (AId X) (ANum 1)  {{fun st => st X <= 5 }}.
Proof.
  eapply hoare_consequence_pre.
  - apply hoare_asgn.
  - unfold "->>". intros. unfold assn_sub. simpl. rewrite t_update_eq. assumption.
Qed.
(* here with apply
  apply hoare_consequence_pre
  with (P' := (fun st => st X <= 5) [X |-> APlus (AId X) (ANum 1)]).
  - apply hoare_asgn.
  - unfold "->>". intros. unfold assn_sub. simpl. rewrite t_update_eq. assumption.
Qed.
*)

Example ass_sub_ex2' :
  {{ fun st => 0 <= 3 /\ 3 <= 5 }}  X ::= ANum 3  {{ fun st => 0 <= st X /\ st X <= 5 }}.
Proof.
  apply hoare_consequence_pre
  with (P' := (fun st => 0 <= st X /\ st X <= 5) [X |-> (ANum 3)]).
  - apply hoare_asgn.
  - unfold "->>". intros. unfold assn_sub. simpl. rewrite t_update_eq. assumption.
Qed.

(** [] *)

(* ================================================================= *)
(** ** Skip *)

(** Since [SKIP] doesn't change the state, it preserves any
    property [P]:

      --------------------  (hoare_skip)
      {{ P }} SKIP {{ P }}
*)

Theorem hoare_skip : forall P,
     {{P}} SKIP {{P}}.
Proof.
  intros P st st' H HP. inversion H. subst.
  assumption.  Qed.

(* ================================================================= *)
(** ** Sequencing *)

(** More interestingly, if the command [c1] takes any state where
    [P] holds to a state where [Q] holds, and if [c2] takes any
    state where [Q] holds to one where [R] holds, then doing [c1]
    followed by [c2] will take any state where [P] holds to one
    where [R] holds:

        {{ P }} c1 {{ Q }}
        {{ Q }} c2 {{ R }}
       ---------------------  (hoare_seq)
       {{ P }} c1;;c2 {{ R }}
*)

Theorem hoare_seq : forall P Q R c1 c2,
     {{Q}} c2 {{R}} ->
     {{P}} c1 {{Q}} ->
     {{P}} c1;;c2 {{R}}.
Proof.
  intros P Q R c1 c2 H1 H2 st st' H12 Pre.
  inversion H12; subst.
  apply (H1 st'0 st'); try assumption.
  apply (H2 st st'0); assumption. Qed.

(** Note that, in the formal rule [hoare_seq], the premises are
    given in backwards order ([c2] before [c1]).  This matches the
    natural flow of information in many of the situations where we'll
    use the rule, since the natural way to construct a Hoare-logic
    proof is to begin at the end of the program (with the final
    postcondition) and push postconditions backwards through commands
    until we reach the beginning. *)

(** Informally, a nice way of displaying a proof using the sequencing
    rule is as a "decorated program" where the intermediate assertion
    [Q] is written between [c1] and [c2]:

      {{ a = n }}
    X ::= a;;
      {{ X = n }}    <---- decoration for Q
    SKIP
      {{ X = n }}
*)

(** Here's an example of a program involving both assignment and
    sequencing. *)

Example hoare_asgn_example3 : forall a n,
  {{fun st => aeval st a = n}}
  (X ::= a;; SKIP)
  {{fun st => st X = n}}.
Proof.
  intros a n. eapply hoare_seq.
  - (* right part of seq *)
    apply hoare_skip.
  - (* left part of seq *)
    eapply hoare_consequence_pre. apply hoare_asgn.
    intros st H. subst. reflexivity.
Qed.

(** We typically use [hoare_seq] in conjunction with
    [hoare_consequence_pre] and the [eapply] tactic, as in this
    example. *)

(** **** Exercise: 2 stars (hoare_asgn_example4)  *)
(** Translate this "decorated program" into a formal proof:

                   {{ True }} ->>
                   {{ 1 = 1 }}
    X ::= 1;;
                   {{ X = 1 }} ->>
                   {{ X = 1 /\ 2 = 2 }}
    Y ::= 2
                   {{ X = 1 /\ Y = 2 }}
*)

Example hoare_asgn_example4 :
  {{fun st => True}} (X ::= (ANum 1);; Y ::= (ANum 2))
  {{fun st => st X = 1 /\ st Y = 2}}.
Proof.
  apply hoare_seq with (Q := fun st => st X = 1).
  - apply hoare_consequence_pre with ((fun st => st X = 1 /\ st Y = 2) [Y |-> ANum 2]).
    + apply hoare_asgn.
    + unfold "->>", assn_sub. intros. simpl. split.
      * unfold t_update. destruct (beq_id Y X) eqn:Heq; [inversion Heq | assumption].
      * apply t_update_eq.
  - apply hoare_consequence_pre with ((fun st => st X = 1) [X |-> ANum 1]).
    + apply hoare_asgn.
    + unfold "->>", assn_sub. intros. simpl. apply t_update_eq.
Qed.
(* a lot easier with eapply
  eapply hoare_seq; [eapply hoare_asgn |].
  eapply hoare_consequence_pre; [apply hoare_asgn |].
  unfold "->>", assn_sub. intros. simpl. split.
  - rewrite t_update_permute.
    + rewrite t_update_eq. reflexivity.
    + unfold not. intros. inversion H0.
  - apply t_update_eq.
Qed.
*)

(** [] *)

(** **** Exercise: 3 stars (swap_exercise)  *)
(** Write an Imp program [c] that swaps the values of [X] and [Y] and
    show that it satisfies the following specification:

      {{X <= Y}} c {{Y <= X}}
*)

Definition swap_program : com :=
  Z ::= AId X;;
  X ::= AId Y;;
  Y ::= AId Z.

Theorem swap_exercise :
  {{fun st => st X <= st Y}}
  swap_program
  {{fun st => st Y <= st X}}.
Proof.
  eapply hoare_seq.
  - eapply hoare_seq; apply hoare_asgn.
  - eapply hoare_consequence_pre; [apply hoare_asgn |].
    unfold "->>", assn_sub. intros. simpl.
    apply H. (* why is this possible!?*)
Qed.
(** [] *)

(** **** Exercise: 3 stars (hoarestate1)  *)
(** Explain why the following proposition can't be proven:

      forall (a : aexp) (n : nat),
         {{fun st => aeval st a = n}}
         (X ::= (ANum 3);; Y ::= a)
         {{fun st => st Y = n}}.
*)

(** Because a can depend on the state it is evaluated in, and since
 it is another state we're in when we assign Y we cannot say that a
 evals to the same n again
 **)
(** [] *)

(* ================================================================= *)
(** ** Conditionals *)

(** What sort of rule do we want for reasoning about conditional
    commands?

    Certainly, if the same assertion [Q] holds after executing
    either of the branches, then it holds after the whole conditional.
    So we might be tempted to write:

              {{P}} c1 {{Q}}
              {{P}} c2 {{Q}}
      --------------------------------
      {{P}} IFB b THEN c1 ELSE c2 {{Q}}

   However, this is rather weak. For example, using this rule,
   we cannot show

     {{ True }}
     IFB X == 0
     THEN Y ::= 2
     ELSE Y ::= X + 1
     FI
     {{ X <= Y }}

   since the rule tells us nothing about the state in which the
   assignments take place in the "then" and "else" branches. *)

(** Fortunately, we can say something more precise.  In the
    "then" branch, we know that the boolean expression [b] evaluates to
    [true], and in the "else" branch, we know it evaluates to [false].
    Making this information available in the premises of the rule gives
    us more information to work with when reasoning about the behavior
    of [c1] and [c2] (i.e., the reasons why they establish the
    postcondition [Q]). *)
(**

              {{P /\  b}} c1 {{Q}}
              {{P /\ ~b}} c2 {{Q}}
      ------------------------------------  (hoare_if)
      {{P}} IFB b THEN c1 ELSE c2 FI {{Q}}
*)

(** To interpret this rule formally, we need to do a little work.
    Strictly speaking, the assertion we've written, [P /\ b], is the
    conjunction of an assertion and a boolean expression -- i.e., it
    doesn't typecheck.  To fix this, we need a way of formally
    "lifting" any bexp [b] to an assertion.  We'll write [bassn b] for
    the assertion "the boolean expression [b] evaluates to [true] (in
    the given state)." *)

Definition bassn b : Assertion :=
  fun st => (beval st b = true).

(** A couple of useful facts about [bassn]: *)

Lemma bexp_eval_true : forall b st,
  beval st b = true -> (bassn b) st.
Proof.
  intros b st Hbe.
  unfold bassn. assumption.  Qed.

Lemma bexp_eval_false : forall b st,
  beval st b = false -> ~ ((bassn b) st).
Proof.
  intros b st Hbe contra.
  unfold bassn in contra.
  rewrite -> contra in Hbe. inversion Hbe.  Qed.

(** Now we can formalize the Hoare proof rule for conditionals
    and prove it correct. *)

Theorem hoare_if : forall P Q b c1 c2,
  {{fun st => P st /\ bassn b st}} c1 {{Q}} ->
  {{fun st => P st /\ ~(bassn b st)}} c2 {{Q}} ->
  {{P}} (IFB b THEN c1 ELSE c2 FI) {{Q}}.
Proof.
  intros P Q b c1 c2 HTrue HFalse st st' HE HP.
  inversion HE; subst.
  - (* b is true *)
    apply (HTrue st st').
      assumption.
      split. assumption.
             apply bexp_eval_true. assumption.
  - (* b is false *)
    apply (HFalse st st').
      assumption.
      split. assumption.
             apply bexp_eval_false. assumption. Qed.

(* ----------------------------------------------------------------- *)
(** *** Example *)

(** Here is a formal proof that the program we used to motivate the
    rule satisfies the specification we gave. *)

Example if_example :
    {{fun st => True}}
  IFB (BEq (AId X) (ANum 0))
    THEN (Y ::= (ANum 2))
    ELSE (Y ::= APlus (AId X) (ANum 1))
  FI
    {{fun st => st X <= st Y}}.
Proof.
  (* WORKED IN CLASS *)
  apply hoare_if.
  - (* Then *)
    eapply hoare_consequence_pre. apply hoare_asgn.
    unfold bassn, assn_sub, t_update, assert_implies.
    simpl. intros st [_ H].
    apply beq_nat_true in H.
    rewrite H. omega.
  - (* Else *)
    eapply hoare_consequence_pre. apply hoare_asgn.
    unfold assn_sub, t_update, assert_implies.
    simpl; intros st _. omega.
Qed.

(** **** Exercise: 2 stars (if_minus_plus)  *)
(** Prove the following hoare triple using [hoare_if]: *)

Theorem if_minus_plus :
  {{fun st => True}}
  IFB (BLe (AId X) (AId Y))
    THEN (Z ::= AMinus (AId Y) (AId X))
    ELSE (Y ::= APlus (AId X) (AId Z))
  FI
  {{fun st => st Y = st X + st Z}}.
Proof.
  apply hoare_if; (eapply hoare_consequence_pre; [apply hoare_asgn |];
                  unfold bassn, assn_sub, "->>"; intros; destruct H).
  - simpl. rewrite t_update_eq. rewrite t_update_neq.
    + rewrite Nat.add_sub_assoc. rewrite minus_plus; reflexivity.
      simpl in H0. apply (leb_complete _ _ H0).
    + unfold not. intros. inversion H1.
  - rewrite ?t_update_eq. simpl. rewrite 2!t_update_neq;
                                   [reflexivity | |];
                                   unfold not; intros; inversion H1.
Qed.

(* ----------------------------------------------------------------- *)
(** *** Exercise: One-sided conditionals *)

(** **** Exercise: 4 stars (if1_hoare)  *)

(** In this exercise we consider extending Imp with "one-sided
    conditionals" of the form [IF1 b THEN c FI]. Here [b] is a
    boolean expression, and [c] is a command. If [b] evaluates to
    [true], then command [c] is evaluated. If [b] evaluates to
    [false], then [IF1 b THEN c FI] does nothing.

    We recommend that you do this exercise before the ones that
    follow, as it should help solidify your understanding of the
    material. *)

(** The first step is to extend the syntax of commands and introduce
    the usual notations.  (We've done this for you.  We use a separate
    module to prevent polluting the global name space.) *)

Module If1.

Inductive com : Type :=
  | CSkip : com
  | CAss : id -> aexp -> com
  | CSeq : com -> com -> com
  | CIf : bexp -> com -> com -> com
  | CWhile : bexp -> com -> com
  | CIf1 : bexp -> com -> com.

Notation "'SKIP'" :=
  CSkip.
Notation "c1 ;; c2" :=
  (CSeq c1 c2) (at level 80, right associativity).
Notation "X '::=' a" :=
  (CAss X a) (at level 60).
Notation "'WHILE' b 'DO' c 'END'" :=
  (CWhile b c) (at level 80, right associativity).
Notation "'IFB' e1 'THEN' e2 'ELSE' e3 'FI'" :=
  (CIf e1 e2 e3) (at level 80, right associativity).
Notation "'IF1' b 'THEN' c 'FI'" :=
  (CIf1 b c) (at level 80, right associativity).

(** Next we need to extend the evaluation relation to accommodate
    [IF1] branches.  This is for you to do... What rule(s) need to be
    added to [ceval] to evaluate one-sided conditionals? *)

Reserved Notation "c1 '/' st '\\' st'" (at level 40, st at level 39).

Inductive ceval : com -> state -> state -> Prop :=
  | E_Skip : forall st : state, SKIP / st \\ st
  | E_Ass : forall (st : state) (a1 : aexp) (n : nat) (X : id),
            aeval st a1 = n -> (X ::= a1) / st \\ t_update st X n
  | E_Seq : forall (c1 c2 : com) (st st' st'' : state),
            c1 / st \\ st' -> c2 / st' \\ st'' -> (c1 ;; c2) / st \\ st''
  | E_IfTrue : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
               beval st b1 = true ->
               c1 / st \\ st' -> (IFB b1 THEN c1 ELSE c2 FI) / st \\ st'
  | E_IfFalse : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
                beval st b1 = false ->
                c2 / st \\ st' -> (IFB b1 THEN c1 ELSE c2 FI) / st \\ st'
  | E_WhileEnd : forall (b1 : bexp) (st : state) (c1 : com),
                 beval st b1 = false -> (WHILE b1 DO c1 END) / st \\ st
  | E_WhileLoop : forall (st st' st'' : state) (b1 : bexp) (c1 : com),
                  beval st b1 = true ->
                  c1 / st \\ st' ->
                  (WHILE b1 DO c1 END) / st' \\ st'' ->
                  (WHILE b1 DO c1 END) / st \\ st''
  | E_If1True : forall (st st' : state) (b1 : bexp) (c1 : com),
               beval st b1 = true ->
               c1 / st \\ st' -> (IF1 b1 THEN c1 FI) / st \\ st'
  | E_If1False : forall (st st' : state) (b1 : bexp) (c1 : com),
                beval st b1 = false ->
                (IF1 b1 THEN c1 FI) / st \\ st

  where "c1 '/' st '\\' st'" := (ceval c1 st st').

(** Now we repeat (verbatim) the definition and notation of Hoare triples. *)

Definition hoare_triple (P:Assertion) (c:com) (Q:Assertion) : Prop :=
  forall st st',
       c / st \\ st'  ->
       P st  ->
       Q st'.

Notation "{{ P }}  c  {{ Q }}" := (hoare_triple P c Q)
                                  (at level 90, c at next level)
                                  : hoare_spec_scope.

(** Finally, we (i.e., you) need to state and prove a theorem,
    [hoare_if1], that expresses an appropriate Hoare logic proof rule
    for one-sided conditionals. Try to come up with a rule that is
    both sound and as precise as possible. *)

Theorem hoare_if1 : forall P Q b c1,
  {{fun st => P st /\ bassn b st}} c1 {{Q}} ->
  ((fun st => P st /\ ~(bassn b st)) ->> Q) ->
  {{P}} (IF1 b THEN c1 FI) {{Q}}.
  Proof.
    intros P Q b c1 H1 H2 st st' H3 HP.
    inversion H3; subst.
    - apply (H1 st st' H7). split; assumption.
    - apply H2. split; [assumption|]. congruence.
  Qed.

(** For full credit, prove formally [hoare_if1_good] that your rule is
    precise enough to show the following valid Hoare triple:

  {{ X + Y = Z }}
  IF1 Y <> 0 THEN
    X ::= X + Y
  FI
  {{ X = Z }}
*)

(** Hint: Your proof of this triple may need to use the other proof
    rules also. Because we're working in a separate module, you'll
    need to copy here the rules you find necessary. *)

Lemma hoare_if1_good :
  {{ fun st => st X + st Y = st Z }}
  IF1 BNot (BEq (AId Y) (ANum 0)) THEN
    X ::= APlus (AId X) (AId Y)
  FI
  {{ fun st => st X = st Z }}.
Proof.
  intros st st' H1 H2. inversion H1; subst.
  - inversion H6. subst. simpl.
    rewrite H2. reflexivity.
  - simpl in *. rewrite negb_false_iff in H5.
    pose proof (beq_nat_true _ _ H5).
    rewrite H in H2. rewrite plus_0_r in H2. apply H2.
  Qed.

End If1.
(** [] *)

(* ================================================================= *)
(** ** Loops *)

(** Finally, we need a rule for reasoning about while loops. *)

(** Suppose we have a loop

      WHILE b DO c END

    and we want to find a pre-condition [P] and a post-condition
    [Q] such that

      {{P}} WHILE b DO c END {{Q}}

    is a valid triple. *)

(** First of all, let's think about the case where [b] is false at the
    beginning -- i.e., let's assume that the loop body never executes
    at all.  In this case, the loop behaves like [SKIP], so we might
    be tempted to write: *)

(**

      {{P}} WHILE b DO c END {{P}}.
*)

(** But, as we remarked above for the conditional, we know a
    little more at the end -- not just [P], but also the fact
    that [b] is false in the current state.  So we can enrich the
    postcondition a little: *)
(**

      {{P}} WHILE b DO c END {{P /\ ~b}}
*)

(** What about the case where the loop body _does_ get executed?
    In order to ensure that [P] holds when the loop finally
    exits, we certainly need to make sure that the command [c]
    guarantees that [P] holds whenever [c] is finished.
    Moreover, since [P] holds at the beginning of the first
    execution of [c], and since each execution of [c]
    re-establishes [P] when it finishes, we can always assume
    that [P] holds at the beginning of [c].  This leads us to the
    following rule: *)
(**

                   {{P}} c {{P}}
        -----------------------------------
        {{P}} WHILE b DO c END {{P /\ ~b}}
*)
(** This is almost the rule we want, but again it can be improved a
    little: at the beginning of the loop body, we know not only that
    [P] holds, but also that the guard [b] is true in the current
    state.  This gives us a little more information to use in
    reasoning about [c] (showing that it establishes the invariant by
    the time it finishes).  This gives us the final version of the
    rule:
*)
(**

               {{P /\ b}} c {{P}}
        -----------------------------------  (hoare_while)
        {{P}} WHILE b DO c END {{P /\ ~b}}

    The proposition [P] is called an _invariant_ of the loop.
*)

Lemma hoare_while : forall P b c,
  {{fun st => P st /\ bassn b st}} c {{P}} ->
  {{P}} WHILE b DO c END {{fun st => P st /\ ~ (bassn b st)}}.
Proof.
  intros P b c Hhoare st st' He HP.
  (* Like we've seen before, we need to reason by induction
     on [He], because, in the "keep looping" case, its hypotheses
     talk about the whole loop instead of just [c]. *)
  remember (WHILE b DO c END) as wcom eqn:Heqwcom.
  induction He;
    try (inversion Heqwcom); subst; clear Heqwcom.
  - (* E_WhileEnd *)
    split. assumption. apply bexp_eval_false. assumption.
  - (* E_WhileLoop *)
    apply IHHe2. reflexivity.
    apply (Hhoare st st'). assumption.
      split. assumption. apply bexp_eval_true. assumption.
Qed.

(** One subtlety in the terminology is that calling some assertion [P]
    a "loop invariant" doesn't just mean that it is preserved by the
    body of the loop in question (i.e., [{{P}} c {{P}}], where [c] is
    the loop body), but rather that [P] _together with the fact that
    the loop's guard is true_ is a sufficient precondition for [c] to
    ensure [P] as a postcondition.

    This is a slightly (but significantly) weaker requirement.  For
    example, if [P] is the assertion [X = 0], then [P] _is_ an
    invariant of the loop

    WHILE X = 2 DO X := 1 END

    although it is clearly _not_ preserved by the body of the
    loop. *)

Example while_example :
    {{fun st => st X <= 3}}
  WHILE (BLe (AId X) (ANum 2))
  DO X ::= APlus (AId X) (ANum 1) END
    {{fun st => st X = 3}}.
Proof.
  eapply hoare_consequence_post.
  apply hoare_while.
  eapply hoare_consequence_pre.
  apply hoare_asgn.
  unfold bassn, assn_sub, assert_implies, t_update. simpl.
    intros st [H1 H2]. apply leb_complete in H2. omega.
  unfold bassn, assert_implies. intros st [Hle Hb].
    simpl in Hb. destruct (leb (st X) 2) eqn : Heqle.
    exfalso. apply Hb; reflexivity.
    apply leb_iff_conv in Heqle. omega.
Qed.

(** We can use the while rule to prove the following Hoare triple,
    which may seem surprising at first... *)

Theorem always_loop_hoare : forall P Q,
  {{P}} WHILE BTrue DO SKIP END {{Q}}.
Proof.
  (* WORKED IN CLASS *)
  intros P Q.
  apply hoare_consequence_pre with (P' := fun st : state => True).
  eapply hoare_consequence_post.
  apply hoare_while.
  - (* Loop body preserves invariant *)
    apply hoare_post_true. intros st. apply I.
  - (* Loop invariant and negated guard imply postcondition *)
    simpl. intros st [Hinv Hguard].
    exfalso. apply Hguard. reflexivity.
  - (* Precondition implies invariant *)
    intros st H. constructor.  Qed.

(** Of course, this result is not surprising if we remember that
    the definition of [hoare_triple] asserts that the postcondition
    must hold _only_ when the command terminates.  If the command
    doesn't terminate, we can prove anything we like about the
    post-condition. *)

(** Hoare rules that only talk about terminating commands are
    often said to describe a logic of "partial" correctness.  It is
    also possible to give Hoare rules for "total" correctness, which
    build in the fact that the commands terminate. However, in this
    course we will only talk about partial correctness. *)

(* ----------------------------------------------------------------- *)
(** *** Exercise: [REPEAT] *)

(** **** Exercise: 4 stars, advanced (hoare_repeat)  *)
(** In this exercise, we'll add a new command to our language of
    commands: [REPEAT] c [UNTIL] a [END]. You will write the
    evaluation rule for [repeat] and add a new Hoare rule to
    the language for programs involving it. *)

Module RepeatExercise.

Inductive com : Type :=
  | CSkip : com
  | CAsgn : id -> aexp -> com
  | CSeq : com -> com -> com
  | CIf : bexp -> com -> com -> com
  | CWhile : bexp -> com -> com
  | CRepeat : com -> bexp -> com.

(** [REPEAT] behaves like [WHILE], except that the loop guard is
    checked _after_ each execution of the body, with the loop
    repeating as long as the guard stays _false_.  Because of this,
    the body will always execute at least once. *)

Notation "'SKIP'" :=
  CSkip.
Notation "c1 ;; c2" :=
  (CSeq c1 c2) (at level 80, right associativity).
Notation "X '::=' a" :=
  (CAsgn X a) (at level 60).
Notation "'WHILE' b 'DO' c 'END'" :=
  (CWhile b c) (at level 80, right associativity).
Notation "'IFB' e1 'THEN' e2 'ELSE' e3 'FI'" :=
  (CIf e1 e2 e3) (at level 80, right associativity).
Notation "'REPEAT' e1 'UNTIL' b2 'END'" :=
  (CRepeat e1 b2) (at level 80, right associativity).

(** Add new rules for [REPEAT] to [ceval] below.  You can use the rules
    for [WHILE] as a guide, but remember that the body of a [REPEAT]
    should always execute at least once, and that the loop ends when
    the guard becomes true.  Then update the [ceval_cases] tactic to
    handle these added cases.  *)

Inductive ceval : state -> com -> state -> Prop :=
  | E_Skip : forall st,
      ceval st SKIP st
  | E_Ass  : forall st a1 n X,
      aeval st a1 = n ->
      ceval st (X ::= a1) (t_update st X n)
  | E_Seq : forall c1 c2 st st' st'',
      ceval st c1 st' ->
      ceval st' c2 st'' ->
      ceval st (c1 ;; c2) st''
  | E_IfTrue : forall st st' b1 c1 c2,
      beval st b1 = true ->
      ceval st c1 st' ->
      ceval st (IFB b1 THEN c1 ELSE c2 FI) st'
  | E_IfFalse : forall st st' b1 c1 c2,
      beval st b1 = false ->
      ceval st c2 st' ->
      ceval st (IFB b1 THEN c1 ELSE c2 FI) st'
  | E_WhileEnd : forall b1 st c1,
      beval st b1 = false ->
      ceval st (WHILE b1 DO c1 END) st
  | E_WhileLoop : forall st st' st'' b1 c1,
      beval st b1 = true ->
      ceval st c1 st' ->
      ceval st' (WHILE b1 DO c1 END) st'' ->
      ceval st (WHILE b1 DO c1 END) st''
  | E_RepeatEnd : forall b1 st st' c1,
      beval st' b1 = true ->
      ceval st c1 st' ->
      ceval st (REPEAT c1 UNTIL b1 END) st'
  | E_RepeatLoop : forall b1 st st' st'' c1,
      beval st' b1 = false ->
      ceval st c1 st' ->
      ceval st' (REPEAT c1 UNTIL b1 END) st'' ->
      ceval st (REPEAT c1 UNTIL b1 END) st''.

(** A couple of definitions from above, copied here so they use the
    new [ceval]. *)

Notation "c1 '/' st '\\' st'" := (ceval st c1 st')
                                 (at level 40, st at level 39).

Definition hoare_triple (P:Assertion) (c:com) (Q:Assertion)
                        : Prop :=
  forall st st', (c / st \\ st') -> P st -> Q st'.

Notation "{{ P }}  c  {{ Q }}" :=
  (hoare_triple P c Q) (at level 90, c at next level).

(** To make sure you've got the evaluation rules for [REPEAT] right,
    prove that [ex1_repeat evaluates correctly. *)

Definition ex1_repeat :=
  REPEAT
    X ::= ANum 1;;
    Y ::= APlus (AId Y) (ANum 1)
  UNTIL (BEq (AId X) (ANum 1)) END.

Theorem ex1_repeat_works :
  ex1_repeat / empty_state \\
               t_update (t_update empty_state X 1) Y 1.
Proof.
  unfold ex1_repeat. constructor; [reflexivity |].
  eapply E_Seq; constructor; reflexivity.
Qed.

(** Now state and prove a theorem, [hoare_repeat], that expresses an
    appropriate proof rule for [repeat] commands.  Use [hoare_while]
    as a model, and try to make your rule as precise as possible. *)
Lemma hoare_while' : forall P b c,
  {{fun st => P st /\ bassn b st}} c {{P}} ->
  {{P}} WHILE b DO c END {{fun st => P st /\ ~ (bassn b st)}}.
Proof.
  intros P b c Hhoare st st' He HP.
  (* Like we've seen before, we need to reason by induction
     on [He], because, in the "keep looping" case, its hypotheses
     talk about the whole loop instead of just [c]. *)
  remember (WHILE b DO c END) as wcom eqn:Heqwcom.
  induction He;
    try (inversion Heqwcom); subst; clear Heqwcom.
  - (* E_WhileEnd *)
    split. assumption. apply bexp_eval_false. assumption.
  - (* E_WhileLoop *)
    apply IHHe2. reflexivity.
    apply (Hhoare st st'). assumption.
      split. assumption. apply bexp_eval_true. assumption.
Qed.
(*
                        {Q /\ ~b} c {Q}
                   ----------------------------------
  {P} c {Q}       {Q} WHILE ~b DO c END {Q /\ b}
  -------------------------------------------------------
                  c ; WHILE ~b DO c END
*)
Lemma hoare_repeat : forall P Q b c,
  {{P}} c {{Q}} -> {{fun st => Q st /\ ~(bassn b st)}} c {{Q}} ->
  {{P}} REPEAT c UNTIL b END {{fun st => Q st /\ bassn b st}}.
Proof.
  intros P Q b c H1 H2 st st' Hc HP.
  unfold hoare_triple in *.
  remember (REPEAT c UNTIL b END) as Hrem eqn:HremEq.
  induction Hc; intros; inversion HremEq; subst.
  - split; [apply (H1 _ _ Hc HP) | apply (bexp_eval_true _ _ H)].
  Abort.

Lemma hoare_repeat' : forall P Q b c,
    {{P}} c {{Q}} ->
    (fun st => Q st /\ ~(bassn b st)) ->> P ->
    {{P}} REPEAT c UNTIL b END {{fun st => Q st /\ bassn b st}}.
Proof.
  intros P Q b c Hc HInv st st' He HP.
  unfold "->>" in *.
  remember (REPEAT c UNTIL b END) as wcom eqn:Heqwcom.
  unfold hoare_triple in *.
  induction He; inversion Heqwcom; subst; clear Heqwcom.
  - split; [apply (Hc _ _ He HP)|].
    apply (bexp_eval_true _ _ H).
  - apply IHHe2; [reflexivity |]. apply HInv. split; [apply (Hc _ _ He1 HP) |].
    apply (bexp_eval_false _ _ H).
Qed.

(** For full credit, make sure (informally) that your rule can be used
    to prove the following valid Hoare triple:

  {{ X > 0 }}
  REPEAT
    Y ::= X;;
    X ::= X - 1
  UNTIL X = 0 END
  {{ X = 0 /\ Y > 0 }}
*)

(** copy-paste lemmas into module **)

Theorem hoare_consequence_pre : forall (P P' Q : Assertion) c,
  {{P'}} c {{Q}} ->
  P ->> P' ->
  {{P}} c {{Q}}.
Proof.
  intros P P' Q c Hhoare Himp.
  intros st st' Hc HP. apply (Hhoare st st').
  assumption. apply Himp. assumption. Qed.

Theorem hoare_consequence_post : forall (P Q Q' : Assertion) c,
  {{P}} c {{Q'}} ->
  Q' ->> Q ->
  {{P}} c {{Q}}.
Proof.
  intros P Q Q' c Hhoare Himp.
  intros st st' Hc HP.
  apply Himp.
  apply (Hhoare st st').
  assumption. assumption. Qed.

Theorem hoare_consequence : forall (P P' Q Q' : Assertion) c,
  {{P'}} c {{Q'}} ->
  P ->> P' ->
  Q' ->> Q ->
  {{P}} c {{Q}}.
Proof.
  intros P P' Q Q' c Hht HPP' HQ'Q.
  apply hoare_consequence_pre with (P' := P').
  apply hoare_consequence_post with (Q' := Q').
  assumption. assumption. assumption.  Qed.

Theorem hoare_seq : forall P Q R c1 c2,
     {{Q}} c2 {{R}} ->
     {{P}} c1 {{Q}} ->
     {{P}} c1;;c2 {{R}}.
Proof.
  intros P Q R c1 c2 H1 H2 st st' H12 Pre.
  inversion H12; subst.
  apply (H1 st'0 st'); try assumption.
  apply (H2 st st'0); assumption. Qed.

Theorem hoare_asgn : forall Q X a,
  {{Q [X |-> a]}} (X ::= a) {{Q}}.
Proof.
  unfold hoare_triple.
  intros Q X a st st' HE HQ.
  inversion HE. subst.
  unfold assn_sub in HQ. assumption.  Qed.

(**
{{ X > 0 }}
  REPEAT
  Y ::= AId X;;
  X ::= AMinus (AId X) (ANum 1)
  UNTIL (BEq (AId X) (ANum 0)) END
{{ X = 0 /\ Y > 0}}

So P = {{X > 0}}, Q = {{Y > 0}}, b = {{X = 0}}

Entry:
{{ X > 0 }}
{{ X > 0 /\ Y = Y }}
Y ::= AId X;;
{{ X > 0 /\ Y = X }}
{{ Y > 0 }}
X ::= AMinus (AId X) (ANum 1)
{{ Y > 0 }}
{{ Y > 0 }}

Invariant:
{{ Y > 0 /\ X /= 0 }}
{{ Y = Y /\ Y > 0 /\ X /= 0 }}
Y ::= AId X;;
{{ Y = X /\ X > 0 /\ X /= 0 }}
{{ Y > 0 }}
X ::= AMinus (AId X) (ANum 1)
{{ Y > 0 }}

Coq proof below.
I'm pretty sure it could've been written simpler with more eapply and hoare_asgn,
but it just confused me, so I brute-forced it!
**)

Theorem hoare_repeat_test :
  {{ fun st => st X > 0 }}
    REPEAT
    Y ::= AId X;;
    X ::= AMinus (AId X) (ANum 1)
    UNTIL (BEq (AId X) (ANum 0)) END
  {{ fun st => st X = 0 /\ st Y > 0 }}.
Proof.
  apply hoare_consequence_post with (Q' := fun st => st Y > 0 /\ bassn (BEq (AId X) (ANum 0)) st).
  - apply hoare_repeat.
    + apply hoare_seq with (Q := fun st => st Y > 0).
      * unfold hoare_triple. intros. inversion H. subst. simpl in *. rewrite t_update_neq.
        assumption. unfold not. intros. inversion H1.
      * unfold hoare_triple. intros. inversion H. subst. simpl in *. rewrite t_update_eq. assumption.
    + unfold "->>". intros. destruct H. unfold not in H0. simpl in H0.
      unfold bassn in H0. simpl in H0. rewrite beq_nat_true_iff in H0.
      destruct (gt_0_eq (st X)); [assumption |].
      symmetry in H1. contradiction (H0 H1).
  - unfold "->>". unfold bassn. simpl. intros. rewrite beq_nat_true_iff in H.
    rewrite and_comm. assumption.
Qed.

End RepeatExercise.
(** [] *)

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

(** So far, we've introduced Hoare Logic as a tool for reasoning about
    Imp programs.  In the reminder of this chapter we'll explore a
    systematic way to use Hoare Logic to prove properties about
    programs. The rules of Hoare Logic are:

             ------------------------------ (hoare_asgn)
             {{Q [X |-> a]}} X::=a {{Q}}

             --------------------  (hoare_skip)
             {{ P }} SKIP {{ P }}

               {{ P }} c1 {{ Q }}
               {{ Q }} c2 {{ R }}
              ---------------------  (hoare_seq)
              {{ P }} c1;;c2 {{ R }}

              {{P /\  b}} c1 {{Q}}
              {{P /\ ~b}} c2 {{Q}}
      ------------------------------------  (hoare_if)
      {{P}} IFB b THEN c1 ELSE c2 FI {{Q}}

               {{P /\ b}} c {{P}}
        -----------------------------------  (hoare_while)
        {{P}} WHILE b DO c END {{P /\ ~b}}

                {{P'}} c {{Q'}}
                   P ->> P'
                   Q' ->> Q
         -----------------------------   (hoare_consequence)
                {{P}} c {{Q}}

    In the next chapter, we'll see how these rules are used to prove
    that programs satisfy specifications of their behavior. *)

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

(** **** Exercise: 3 stars (himp_hoare)  *)
(** In this exercise, we will derive proof rules for the [HAVOC]
    command, which we studied in the last chapter.

    First, we enclose this work in a separate module, and recall the
    syntax and big-step semantics of Himp commands. *)

Module Himp.

Inductive com : Type :=
  | CSkip : com
  | CAsgn : id -> aexp -> com
  | CSeq : com -> com -> com
  | CIf : bexp -> com -> com -> com
  | CWhile : bexp -> com -> com
  | CHavoc : id -> com.

Notation "'SKIP'" :=
  CSkip.
Notation "X '::=' a" :=
  (CAsgn 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' e1 'THEN' e2 'ELSE' e3 'FI'" :=
  (CIf e1 e2 e3) (at level 80, right associativity).
Notation "'HAVOC' X" := (CHavoc X) (at level 60).

Reserved Notation "c1 '/' st '\\' st'" (at level 40, st at level 39).

Inductive ceval : com -> state -> state -> Prop :=
  | E_Skip : forall st : state, SKIP / st \\ st
  | E_Ass : forall (st : state) (a1 : aexp) (n : nat) (X : id),
            aeval st a1 = n -> (X ::= a1) / st \\ t_update st X n
  | E_Seq : forall (c1 c2 : com) (st st' st'' : state),
            c1 / st \\ st' -> c2 / st' \\ st'' -> (c1 ;; c2) / st \\ st''
  | E_IfTrue : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
               beval st b1 = true ->
               c1 / st \\ st' -> (IFB b1 THEN c1 ELSE c2 FI) / st \\ st'
  | E_IfFalse : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
                beval st b1 = false ->
                c2 / st \\ st' -> (IFB b1 THEN c1 ELSE c2 FI) / st \\ st'
  | E_WhileEnd : forall (b1 : bexp) (st : state) (c1 : com),
                 beval st b1 = false -> (WHILE b1 DO c1 END) / st \\ st
  | E_WhileLoop : forall (st st' st'' : state) (b1 : bexp) (c1 : com),
                  beval st b1 = true ->
                  c1 / st \\ st' ->
                  (WHILE b1 DO c1 END) / st' \\ st'' ->
                  (WHILE b1 DO c1 END) / st \\ st''
  | E_Havoc : forall (st : state) (X : id) (n : nat),
              (HAVOC X) / st \\ t_update st X n

  where "c1 '/' st '\\' st'" := (ceval c1 st st').

(** The definition of Hoare triples is exactly as before. Unlike our
    notion of program equivalence, which had subtle consequences with
    occassionally nonterminating commands (exercise [havoc_diverge]),
    this definition is still fully satisfactory. Convince yourself of
    this before proceeding. *)

Definition hoare_triple (P:Assertion) (c:com) (Q:Assertion) : Prop :=
  forall st st', c / st \\ st' -> P st -> Q st'.

Notation "{{ P }}  c  {{ Q }}" := (hoare_triple P c Q)
                                  (at level 90, c at next level)
                                  : hoare_spec_scope.

(** Complete the Hoare rule for [HAVOC] commands below by defining
    [havoc_pre] and prove that the resulting rule is correct. *)

(** this basically says that "Q doesn't care what value X is" **)
Definition havoc_pre (X : id) (Q : Assertion) : Assertion :=
  fun st => forall n, (Q [X |-> (ANum n)]) st.

Theorem hoare_havoc : forall (Q : Assertion) (X : id),
  {{ havoc_pre X Q }} HAVOC X {{ Q }}.
Proof.
  intros Q X st st' c H. unfold havoc_pre in H. inversion c. subst. apply H.
Qed.

End Himp.
(** [] *)

(** $Date: 2016-07-13 12:41:41 -0400 (Wed, 13 Jul 2016) $ *)


From Hammer Require Import Hammer.

Inductive reflect (P Q : Prop) : bool -> Type :=
| reflect_true : P -> reflect P Q true
| reflect_false : Q -> reflect P Q false.

Inductive semi_reflect (P : Prop) : bool -> Type :=
| semi_reflect_true : P -> semi_reflect P true
| semi_reflect_false : semi_reflect P false.

Lemma iff_to_reflect {A B} (P : A -> B -> Prop) (T : A -> B -> bool)  :
(forall x y, T x y = true <-> P x y) ->
(forall x y, reflect (P x y) (~P x y) (T x y)).
Proof. hammer_hook "Consider" "Consider.iff_to_reflect".
intros. case_eq (T x y); intros Hxy; constructor.
apply H. assumption.
intros Hf. apply H in Hf. congruence.
Qed.

Lemma impl_to_semireflect {A B} (P : A -> B -> Prop) (T : A -> B -> bool)  :
(forall x y, T x y = true -> P x y) ->
(forall x y, semi_reflect (P x y) (T x y)).
Proof. hammer_hook "Consider" "Consider.impl_to_semireflect".
intros. case_eq (T x y); intros Hxy; constructor.
apply H; auto.
Qed.

Lemma reflect_true_inv P Q : reflect P Q true -> P.
Proof. hammer_hook "Consider" "Consider.reflect_true_inv".
exact (fun x => match x in reflect _ _ b
return if b then P else ID
with | reflect_true _ _ H => H | reflect_false _ _ H => (fun _ x => x) end).
Qed.

Lemma reflect_false_inv P Q : reflect P Q false -> Q.
Proof. hammer_hook "Consider" "Consider.reflect_false_inv".
exact (fun x => match x in reflect _ _ b
return if b then ID else Q
with | reflect_true _ _ H => fun _ x => x | reflect_false _ _ H => H end).
Qed.

Lemma semi_reflect_true_inv P : semi_reflect P true -> P.
Proof. hammer_hook "Consider" "Consider.semi_reflect_true_inv".
exact (fun x => match x in semi_reflect _ b
return if b then P else ID
with | semi_reflect_true _ H => H | semi_reflect_false _ => (fun _ x => x) end).
Qed.

Class Reflect (T : bool) (P Q : Prop) := _Reflect : reflect P Q T.
Class SemiReflect (T : bool) (P : Prop) := _SemiReflect : semi_reflect P T.

Section boolean_logic.
Ltac t :=
repeat match goal with
| H: Reflect true ?P ?Q |- _ => apply (reflect_true_inv P Q) in H
| H: Reflect false ?P ?Q |- _ => apply (reflect_false_inv P Q) in H
end.

Context {T1 T2 P1 Q1 P2 Q2} {R1 : Reflect T1 P1 Q1} {R2: Reflect T2 P2 Q2}.

Global Instance Reflect_andb : Reflect (T1 && T2)%bool (P1 /\ P2) (Q1 \/ Q2).
Proof. hammer_hook "Consider" "Consider.Reflect_andb".
destruct T1; destruct T2; t; constructor; tauto.
Qed.

Global Instance Reflect_orb : Reflect (T1 || T2)%bool (P1 \/ P2) (Q1 /\ Q2).
Proof. hammer_hook "Consider" "Consider.Reflect_orb".
destruct T1; destruct T2; t; constructor; tauto.
Qed.

Global Instance Reflect_negb : Reflect (negb T1)%bool Q1 P1.
Proof. hammer_hook "Consider" "Consider.Reflect_negb".
destruct T1; t; constructor; tauto.
Qed.

End boolean_logic.

Require Import ExtLib.Core.RelDec.

Section from_rel_dec.
Variable T : Type.
Variable eqt : T -> T -> Prop.
Variable rd : RelDec eqt.
Variable rdc : RelDec_Correct rd.

Global Instance Reflect_RelDecCorrect (a b : T)
: Reflect (rel_dec a b) (eqt a b) (~(eqt a b)).
Proof. hammer_hook "Consider" "Consider.Reflect_RelDecCorrect".
eapply iff_to_reflect.
eapply rel_dec_correct.
Qed.
End from_rel_dec.

Hint Extern 10 (@Reflect (?f ?a ?b) _ _) =>
eapply (@Reflect_RelDecCorrect _ _ (@Build_RelDec _ _ f) _) : typeclass_instances.

Ltac consider f :=
let rec clean :=
match goal with
| |- true = true -> _ => intros _ ; clean
| |- false = true -> _ => discriminate
| |- ?P1 -> ?P2 =>
let H := fresh in intros H ; clean; revert H
| |- _ => idtac
end
in
(repeat match goal with
| [ H : context [ f ] |- _ ] =>
revert H
end) ;
match type of f with
| sumbool _ _ =>
destruct f
| _ =>
match goal with
| _ =>
((let c := constr:(_ : Reflect f _ _) in
case c))
| _ =>
((let c := constr:(_ : SemiReflect f _) in
case c))
| _ =>

case_eq f
end
end ; clean.


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

(****************************************************************************)
(* 	                 Christine Paulin-Mohring                           *)
(*                               July 1st 2000                              *)
(****************************************************************************)
(*i $Id$ i*)

(*********************************************************)
(*s          Axiomatisation of time from reals           *)
(*********************************************************)

Require Export ZArith.

Parameter Time : Set.
Parameter T0 : Time.
Parameter T1 : Time.
Parameter Tplus : Time -> Time -> Time.
Parameter Tmult : Time -> Time -> Time.
Parameter Topp : Time -> Time.
Parameter Tlt : Time -> Time -> Prop.

(**********)
Definition Tle (r1 r2 : Time) : Prop := Tlt r1 r2 \/ r1 = r2.
Definition Tge (r1 r2 : Time) : Prop := Tle r2 r1.
Definition Tgt (r1 r2 : Time) : Prop := Tlt r2 r1.

Hint Unfold Tle Tge Tgt: time.

(**********)
Definition Tminus (r1 r2 : Time) : Time := Tplus r1 (Topp r2).

(*********************************************************)
(*s      Field axioms                                   *)
(*********************************************************)
(*********************************************************)
(*       Addition                                        *)
(*********************************************************)

(**********)
Axiom Tplus_sym : forall r1 r2 : Time, Tplus r1 r2 = Tplus r2 r1.

(**********)
Axiom
  Tplus_assoc :
    forall r1 r2 r3 : Time, Tplus (Tplus r1 r2) r3 = Tplus r1 (Tplus r2 r3).

(**********)
Axiom Tplus_Topp_r : forall r : Time, Tplus r (Topp r) = T0.

Hint Resolve Tplus_sym Tplus_Topp_r: time.

(**********)
Axiom Tplus_T0_r : forall r : Time, Tplus r T0 = r.

Lemma Tplus_T0_l : forall r : Time, Tplus T0 r = r.
intro; rewrite Tplus_sym; apply Tplus_T0_r.
Qed.

Hint Resolve Tplus_T0_r Tplus_T0_l: time.

(**********)

(*********************************************************)
(*s      Order axioms                                    *)
(*********************************************************)
(*********************************************************)
(*       Total Order                                     *)
(*********************************************************)

(**********)
Axiom
  total_order : forall r1 r2 : Time, {Tlt r1 r2} + {r1 = r2} + {Tlt r2 r1}.

(*********************************************************)
(*s      Lower than                                      *)
(*********************************************************)

(**********)
Axiom Tlt_antisym : forall r1 r2 : Time, Tlt r1 r2 -> ~ Tlt r2 r1.

(**********)
Axiom Tlt_trans : forall r1 r2 r3 : Time, Tlt r1 r2 -> Tlt r2 r3 -> Tlt r1 r3.

(**********)
Axiom
  Tlt_compatibility_l :
    forall r r1 r2 : Time, Tlt r1 r2 -> Tlt (Tplus r r1) (Tplus r r2).

Axiom Tlt_T0_T1 : Tlt T0 T1.

Hint Resolve Tlt_T0_T1 Tlt_trans Tlt_compatibility_l Tlt_antisym: time.
(**********)

(**********************************************************)
(*s      Injection from N to Time                         *)
(**********************************************************)

(**********)
Fixpoint INTime (n : nat) : Time :=
  match n with
  | O => T0
  | S O => T1
  | S n => Tplus (INTime n) T1
  end.

(**********************************************************)
(*s      Injection from Z to R                            *)
(**********************************************************)

(**********)
Definition IZTime (z : Z) : Time :=
  match z with
  | Z0 => T0
  | Zpos n => INTime (nat_of_P n)
  | Zneg n => Topp (INTime (nat_of_P n))
  end.

(*********************************************************)
(*       Multiplication                                  *)
(*********************************************************)

(**********)
Axiom Tmult_sym : forall r1 r2 : Time, Tmult r1 r2 = Tmult r2 r1.

(**********)
Axiom
  Tmult_assoc :
    forall r1 r2 r3 : Time, Tmult (Tmult r1 r2) r3 = Tmult r1 (Tmult r2 r3).

Hint Resolve Tmult_sym Tmult_assoc: time.

(**********)
Axiom Tmult_T0_r : forall r : Time, Tmult r T0 = T0.

Lemma Tmult_T0_l : forall r : Time, Tmult T0 r = T0.
intro; rewrite Tmult_sym; apply Tmult_T0_r.
Qed.

(**********)
Axiom Tmult_T1_r : forall r : Time, Tmult r T1 = r.

Lemma Tmult_T1_l : forall r : Time, Tmult T1 r = r.
intro; rewrite Tmult_sym; apply Tmult_T1_r.
Qed.

Hint Resolve Tmult_T0_r Tmult_T0_l: time.


(* PUBLIC DOMAIN *)
Require Export Coq.Vectors.Vector.
Require Export Coq.Lists.List.
Require Import Bool.Bool.
Require Import Logic.FunctionalExtensionality.
Require Import Coq.Program.Wf.
Require Import Lia.

Definition SetVars  := nat.
Definition FuncSymb := nat.
Definition PredSymb := nat.
Record FSV := {
 fs : FuncSymb;
 fsv : nat;
}.
Record PSV := MPSV{
 ps : PredSymb;
 psv : nat;
}.

Section All.
  Variable T : Type.
  Variable P : T -> Prop.

  Fixpoint All (ls : list T) : Prop :=
    match ls with
      | nil => True
      | cons h t => P h /\ All t
    end.
End All.

Section AllT.
  Variable T : Type.
  Variable P : T -> Type.

  Fixpoint AllT (ls : list T) : Type :=
    match ls with
      | nil => True
      | cons h t => (P h) * (AllT t)
    end.
End AllT.

Inductive preTerms : Type :=
| FVC :> SetVars -> preTerms
| FSC (f:FSV) : list preTerms -> preTerms.

Section preTerms_ind'.
  Variable P : preTerms -> Prop.

  Hypothesis preTerms_case1 : forall (sv : SetVars), P (FVC sv).

  Hypothesis preTerms_case2 : forall (n : FSV) (ls : list preTerms),
    All preTerms P ls -> P (FSC n ls).

  Fixpoint preTerms_ind' (tr : preTerms) : P tr.
  Proof.
  destruct tr.
  exact (preTerms_case1 _).
  apply preTerms_case2.
  revert l; fix G 1; intro l.
  destruct l;simpl;trivial.
  split.
  apply preTerms_ind'.
  apply G.
Show Proof.
  Defined.

(** fix preTerms_ind' (tr : preTerms) : P tr :=
   match tr as p return (P p) with
   | FVC s => preTerms_case1 s
   | FSC f l =>
       preTerms_case2 f l
         ((fix G (l0 : list preTerms) : All preTerms P l0 :=
             match l0 as l1 return (All preTerms P l1) with
             | Datatypes.nil => I
             | p :: l1 => conj (preTerms_ind' p) (G l1)
             end) l)
   end **)
End preTerms_ind'.

Section preTerms_rect'.
  Variable P : preTerms -> Type.

  Hypothesis preTerms_case1 : forall (sv : SetVars), P (FVC sv).

  Hypothesis preTerms_case2 : forall (n : FSV) (ls : list preTerms),
    AllT preTerms P ls -> P (FSC n ls).

  Fixpoint preTerms_rect' (tr : preTerms) : P tr.
  Proof.
  destruct tr.
  exact (preTerms_case1 _).
  apply preTerms_case2.
  revert l; fix G 1; intro l.
  destruct l;simpl;trivial.
  split.
  apply preTerms_rect'.
  apply G.
Show Proof.
  Defined.

(** fix preTerms_ind' (tr : preTerms) : P tr :=
   match tr as p return (P p) with
   | FVC s => preTerms_case1 s
   | FSC f l =>
       preTerms_case2 f l
         ((fix G (l0 : list preTerms) : All preTerms P l0 :=
             match l0 as l1 return (All preTerms P l1) with
             | Datatypes.nil => I
             | p :: l1 => conj (preTerms_ind' p) (G l1)
             end) l)
   end **)
End preTerms_rect'.

(*Definitio isTerm (t : preTerms) : Prop.*)

Fixpoint isTerm (t : preTerms) : Prop.
revert t; apply preTerms_rect'; intros.
exact True.
exact ((length ls)=(fsv n)).
Defined.

Eval compute in isTerm (FSC (Build_FSV 0 3) ((FVC 0)::(FVC 0)::(FVC 0)::nil)).

(*elim t using preTerms_ind'.
induction t using preTerms_ind'.*)

Inductive nat_tree : Set :=
| NNode' : nat -> list nat_tree -> nat_tree.

Check Forall.

Fixpoint mh (t : preTerms) : nat :=
  match t with
  | FVC _ => 0
  | FSC f l => S (fold_right (fun t acc => Nat.max acc (mh t)) 0 l)
  end.

Program Fixpoint isTerm isTerm (t : preTerms) {measure (mh t)}: Prop :=
   match t with
   | FVC _ => True
   | FSC f l => (length l = fsv f) /\ (@Forall preTerms (fun q=>isTerm q) l )
(*@All _ _ isTerm l*)
   end.

(isTerm a) /\ (chkd fu l)

Inductive isTerm : preTerms -> Prop :=
| c (pt : preTerms)
(H: match pt with
| FVC sv => True
| FSC f lpt => (Forall isTerm lpt)
end) : isTerm pt.

Inductive Terms : Type :=
| nas (pt : preTerms) (H:isTerm pt): Terms
with isTerm :=
| c (pt : preTerms) () : isTerm pt

Fixpoint isTerm :=
(fix isTerm (t : preTerms) : Prop :=
   match t with
   | FVC _ => True
   | FSC f l => length l = fsv f /\
((fix chkd (fu : preTerms -> Prop )(l : list preTerms) : Prop :=
   match l with
   | nil => True
   | a::l => (isTerm a) /\ (chkd fu l)
   end) isTerm l)
   end).

Fixpoint isTerm (t:preTerms) : Prop.
destruct t.
exact True.
refine (((length l)=(fsv f))/\ _).
exact (List.Forall isTerm l).
Show Proof.
Defined.
destruct l.
exact True.
exact (List.Forall isTerm l).
Defined.
Show Proof.

Unset Elimination Schemes.
Set Elimination Schemes.

Definition Terms_rect (T : Terms -> Type)
                      (H_FVC : forall sv, T (FVC sv))
                      (H_FSC : forall f v, (forall n, T (Vector.nth v n)) -> T (FSC f v)) :=
  fix loopt (t : Terms) : T t :=
    match t with
    | FVC sv  => H_FVC sv
    | FSC f v =>
      let fix loopv s (v : Vector.t Terms s) : forall n, T (Vector.nth v n) :=
        match v with
        | @Vector.nil _ => Fin.case0 _
        | @Vector.cons _ t _ v => fun n => Fin.caseS' n (fun n => T (Vector.nth (Vector.cons _ t _ v) n))
                                                      (loopt t)
                                                      (loopv _ v)
        end in
      H_FSC f v (loopv _ v)
    end.

Definition Terms_ind := Terms_rect.

Fixpoint height (t : Terms) : nat :=
  match t with
  | FVC _ => 0
  | FSC f v => S (Vector.fold_right (fun t acc => Nat.max acc (height t)) v 0)
  end.

(* BEGIN *)
Definition substT :=
(fix substT (t : Terms) (xi : SetVars) (u : Terms) {struct u} : Terms :=
   match u with
   | FVC s => let b := PeanoNat.Nat.eqb s xi in if b then t else FVC s
   | FSC f t0 => FSC f (Vector.map (substT t xi) t0)
   end).

Fixpoint isParamT (xi : SetVars) (t : Terms) {struct t} : bool :=
   match t with
   | FVC s => PeanoNat.Nat.eqb s xi
   | FSC f t0 => Vector.fold_left orb false (Vector.map (isParamT xi) t0)
   end.

Section cor.
Context (X:Type).
Context (fsI:forall(q:FSV),(Vector.t X (fsv q))->X).
Context (prI:forall(q:PSV),(Vector.t X (psv q))->Prop).

Definition teI :=
 (fix teI (val : SetVars -> X) (t : Terms) {struct t} : X :=
   match t with
   | FVC s => val s
   | FSC f t0 => fsI f (Vector.map (teI val) t0)
   end).

(** (\pi + (\xi \mapsto ?) ) **)
Definition cng (val:SetVars -> X) (xi:SetVars) (m:X) (r:SetVars) :=
   match Nat.eqb r xi with
   | true => m
   | false => (val r)
   end.

Section Lem1.
Context (t : Terms).

Definition P(xi : SetVars) (pi : SetVars->X) (u :Terms)
:=(teI pi (substT t xi u))=(teI (cng pi xi (teI pi t)) u).

Definition ap {A B}{a0 a1:A} (f:A->B) (h:a0=a1):((f a0)=(f a1))
:= match h in (_ = y) return (f a0 = f y) with
   | eq_refl => eq_refl
   end.

Fixpoint vec_comp_as (A B C : Type) (f : B -> C) (g : A -> B)
             (n : nat) (t0 : Vector.t A n) {struct t0} :
   Vector.map f (Vector.map g t0) = Vector.map (fun x : A => f (g x)) t0 :=
   match
     t0 as t in (Vector.t _ n0)
     return
       (Vector.map f (Vector.map g t) = Vector.map (fun x : A => f (g x)) t)
   with
   | Vector.nil _ => eq_refl
   | Vector.cons _ h n0 t1 =>
       eq_ind_r
         (fun t : Vector.t C n0 =>
          Vector.cons C (f (g h)) n0 t =
          Vector.cons C (f (g h)) n0 (Vector.map (fun x : A => f (g x)) t1))
         eq_refl (vec_comp_as A B C f g n0 t1)
   end.

(*
Program Fixpoint lem1 (u : Terms) (xi : SetVars) (pi : SetVars -> X)
{measure (height u)} :
   teI pi (substT t xi u) = teI (cng pi xi (teI pi t)) u :=
   match
     u as t0 return (teI pi (substT t xi t0) = teI (cng pi xi (teI pi t)) t0)
   with
   | FVC s =>
       let b := Nat.eqb s xi in
       if b as b0
        return
          (teI pi (if b0 then t else s) = (if b0 then teI pi t else pi s))
       then eq_refl
       else eq_refl
   | FSC f t0 =>
       match
         f as f0
         return
           (forall t1 : Vector.t Terms (fsv f0),
            fsI f0 (Vector.map (teI pi) (Vector.map (substT t xi) t1)) =
            fsI f0 (Vector.map (teI (cng pi xi (teI pi t))) t1))
       with
       | {| fs := fs0; fsv := fsv0 |} =>
           fun t1 : Vector.t Terms (fsv {| fs := fs0; fsv := fsv0 |}) =>
           ap (fsI {| fs := fs0; fsv := fsv0 |})
             (let g :
                Vector.map (teI pi) (Vector.map (substT t xi) t1) =
                Vector.map (fun x : Terms => teI pi (substT t xi x)) t1 :=
                vec_comp_as Terms Terms X (teI pi) (substT t xi) fsv0 t1 in
              eq_ind_r
                (fun t2 : Vector.t X fsv0 =>
                 t2 = Vector.map (teI (cng pi xi (teI pi t))) t1)
                (let Y := fun wm : Terms -> X => Vector.map wm t1 in
                 let a1 := fun x : Terms => teI pi (substT t xi x) in
                 let a2 := teI (cng pi xi (teI pi t)) in
                 let Y1 := Y a1 in
                 let Y2 := Y a2 in
                 ap Y
                   (functional_extensionality
                      (fun x : Terms => teI pi (substT t xi x))
                      (teI (cng pi xi (teI pi t)))
                      (fun x : Terms => lem1 x xi pi))) g)
       end t0
   end.
Next Obligation.*)

Definition lem1 : forall(u :Terms)(xi : SetVars)(pi : SetVars->X), P xi pi u.
Proof. unfold P.
fix lem1 1.
intros.
destruct u as [s|f] .
+ simpl.
  unfold cng.
  destruct (Nat.eqb s xi).
  * reflexivity.
  * simpl.
    reflexivity.
+
  simpl.
  destruct f.
  simpl in * |- *.
  apply ap.

  simpl in t0.
revert fsv0 t0.
fix FFF 1.
intros fsv0 t0.
destruct t0 ; simpl in * |- *; trivial.

Lemma equal_a : forall (A B : Type) (f : A -> B) (a0 a1:A),
  (a0 = a1) -> f a0 = f a1.
Proof.
intros A B f a0 a1 r.
destruct r.
reflexivity.
Defined.

Check (FFF n).
rewrite <- FFF.
Check (functional_extensionality _ _ (FFF fs0)).

Check f_equal.
Check (f_equal (fun g=> Vector.cons X g n
  (Vector.map (teI pi) (Vector.map (substT t xi) t0)))).
apply (f_equal (fun g=> Vector.cons X g n
  (Vector.map (teI pi) (Vector.map (substT t xi) t0)))).
rewrite lem1.
reflexivity.
Defined.

Check functional_extensionality.
rewrite lem1.
apply f_equal.
reflexivity.
Defined.
rewrite -> FFF.

rewrite <- (functional_extensionality _ _ (FFF n)).
rewrite <- (functional_extensionality _ _ (FFF n)).
apply f_equal.

rewrite  FFF.

rewrite <- (functional_extensionality _ _ (FFF n)).
simpl.
Check (@f_equal _ _ _ _ _ _).
apply f_equal.

simpl.

apply functional_extensionality.

  apply ap.

  apply equal_a.

simpl.
  apply ap.

Check (FFF _ (Vector.map (teI pi) (Vector.map (substT t xi) t0)) ).
apply FFF.

  pose (g:= (@vec_comp_as _ _ _ (teI pi) (substT t xi) _ t0)).
  rewrite -> g.
(*Check (@vec_comp_as _ _ _ (teI ) (cng pi xi (teI pi t)) _ ).
  pose (g:= (@vec_comp_as _ _ _ (teI pi) (substT t xi) _ t0)).
  rewrite -> g.*)

pose (Y:=fun wm => @Vector.map Terms X wm fsv0 t0).
pose (a1:=(fun x : Terms => teI pi (substT t xi x))).
pose (a2:=(teI (cng pi xi (teI pi t)))).
pose (Y1:= Y a1).
pose (Y2:= Y a2).
unfold Y in Y1.
unfold Y in Y2.
fold Y1 Y2 in |- *.
apply (@ap _ _ a1 a2 Y).
unfold a1, a2 in |- *.
apply functional_extensionality.
    intro x.

refine (lem1 x xi pi ).
Show Proof.

Admitted.