(** * Imp: Simple Imperative Programs *)

(** In this chapter, we'll take a more serious look at how to use Coq
    to study interesting things outside of itself.  Our case study is
    a _simple imperative programming language_ called Imp, embodying a
    tiny core fragment of conventional mainstream languages such as C
    and Java.  Here is a familiar mathematical function written in
    Imp.

       Z ::= X;;
       Y ::= 1;;
       WHILE ! (Z = 0) DO
         Y ::= Y * Z;;
         Z ::= Z - 1
       END
*)

(** This chapter looks at how to define the _syntax_ and _semantics_
    of Imp; further chapters in _Programming Language Foundations_
    (_Software Foundations_, volume 2) develop a theory of _program
    equivalence_ and introduce _Hoare Logic_, a widely used logic for
    reasoning about imperative programs. *)

Set Warnings "-notation-overridden,-parsing".
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.EqNat.
Require Import Coq.omega.Omega.
Require Import Coq.Lists.List.
Require Import Coq.omega.Omega.
Import ListNotations.

Require Import Maps.

(* ################################################################# *)
(** * Arithmetic and Boolean Expressions *)

(** We'll present Imp in three parts: first a core language of
    _arithmetic and boolean expressions_, then an extension of these
    expressions with _variables_, and finally a language of _commands_
    including assignment, conditions, sequencing, and loops. *)

(* ================================================================= *)
(** ** Syntax *)

Module AExp.

(** These two definitions specify the _abstract syntax_ of
    arithmetic and boolean expressions. *)

Inductive aexp : Type :=
  | ANum : nat -> aexp
  | APlus : aexp -> aexp -> aexp
  | AMinus : aexp -> aexp -> aexp
  | AMult : aexp -> aexp -> aexp.

Inductive bexp : Type :=
  | BTrue : bexp
  | BFalse : bexp
  | BEq : aexp -> aexp -> bexp
  | BLe : aexp -> aexp -> bexp
  | BNot : bexp -> bexp
  | BAnd : bexp -> bexp -> bexp.

(** In this chapter, we'll mostly elide the translation from the
    concrete syntax that a programmer would actually write to these
    abstract syntax trees -- the process that, for example, would
    translate the string ["1+2*3"] to the AST

      APlus (ANum 1) (AMult (ANum 2) (ANum 3)).

    The optional chapter [ImpParser] develops a simple
    implementation of a lexical analyzer and parser that can perform
    this translation.  You do _not_ need to understand that chapter to
    understand this one, but if you haven't taken a course where these
    techniques are covered (e.g., a compilers course) you may want to
    skim it. *)

(** For comparison, here's a conventional BNF (Backus-Naur Form)
    grammar defining the same abstract syntax:

    a ::= nat
        | a + a
        | a - a
        | a * a

    b ::= true
        | false
        | a = a
        | a <= a
        | not b
        | b and b
*)

(** Compared to the Coq version above...

       - The BNF is more informal -- for example, it gives some
         suggestions about the surface syntax of expressions (like the
         fact that the addition operation is written [+] and is an
         infix symbol) while leaving other aspects of lexical analysis
         and parsing (like the relative precedence of [+], [-], and
         [*], the use of parens to explicitly group subexpressions,
         etc.) unspecified.  Some additional information (and human
         intelligence) would be required to turn this description into
         a formal definition, for example when implementing a
         compiler.

         The Coq version consistently omits all this information and
         concentrates on the abstract syntax only.

       - On the other hand, the BNF version is lighter and easier to
         read.  Its informality makes it flexible, a big advantage in
         situations like discussions at the blackboard, where
         conveying general ideas is more important than getting every
         detail nailed down precisely.

         Indeed, there are dozens of BNF-like notations and people
         switch freely among them, usually without bothering to say
         which form of BNF they're using because there is no need to:
         a rough-and-ready informal understanding is all that's
         important.

    It's good to be comfortable with both sorts of notations: informal
    ones for communicating between humans and formal ones for carrying
    out implementations and proofs. *)

(* ================================================================= *)
(** ** Evaluation *)

(** _Evaluating_ an arithmetic expression produces a number. *)

Fixpoint aeval (a : aexp) : nat :=
  match a with
  | ANum n => n
  | APlus a1 a2 => (aeval a1) + (aeval a2)
  | AMinus a1 a2  => (aeval a1) - (aeval a2)
  | AMult a1 a2 => (aeval a1) * (aeval a2)
  end.

Example test_aeval1:
  aeval (APlus (ANum 2) (ANum 2)) = 4.
Proof. reflexivity. Qed.

(** Similarly, evaluating a boolean expression yields a boolean. *)

Fixpoint beval (b : bexp) : bool :=
  match b with
  | BTrue       => true
  | BFalse      => false
  | BEq a1 a2   => beq_nat (aeval a1) (aeval a2)
  | BLe a1 a2   => leb (aeval a1) (aeval a2)
  | BNot b1     => negb (beval b1)
  | BAnd b1 b2  => andb (beval b1) (beval b2)
  end.

(* ================================================================= *)
(** ** Optimization *)

(** We haven't defined very much yet, but we can already get
    some mileage out of the definitions.  Suppose we define a function
    that takes an arithmetic expression and slightly simplifies it,
    changing every occurrence of [0+e] (i.e., [(APlus (ANum 0) e])
    into just [e]. *)

Fixpoint optimize_0plus (a:aexp) : aexp :=
  match a with
  | ANum n =>
      ANum n
  | APlus (ANum 0) e2 =>
      optimize_0plus e2
  | APlus e1 e2 =>
      APlus (optimize_0plus e1) (optimize_0plus e2)
  | AMinus e1 e2 =>
      AMinus (optimize_0plus e1) (optimize_0plus e2)
  | AMult e1 e2 =>
      AMult (optimize_0plus e1) (optimize_0plus e2)
  end.

(** To make sure our optimization is doing the right thing we
    can test it on some examples and see if the output looks OK. *)

Example test_optimize_0plus:
  optimize_0plus (APlus (ANum 2)
                        (APlus (ANum 0)
                               (APlus (ANum 0) (ANum 1))))
  = APlus (ANum 2) (ANum 1).
Proof. reflexivity. Qed.

(** But if we want to be sure the optimization is correct --
    i.e., that evaluating an optimized expression gives the same
    result as the original -- we should prove it. *)

Theorem optimize_0plus_sound: forall a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a. induction a.
  - (* ANum *) reflexivity.
  - (* APlus *) destruct a1.
    + (* a1 = ANum n *) destruct n.
      * (* n = 0 *)  simpl. apply IHa2.
      * (* n <> 0 *) simpl. rewrite IHa2. reflexivity.
    + (* a1 = APlus a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
    + (* a1 = AMinus a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
    + (* a1 = AMult a1_1 a1_2 *)
      simpl. simpl in IHa1. rewrite IHa1.
      rewrite IHa2. reflexivity.
  - (* AMinus *)
    simpl. rewrite IHa1. rewrite IHa2. reflexivity.
  - (* AMult *)
    simpl. rewrite IHa1. rewrite IHa2. reflexivity.  Qed.

(* ################################################################# *)
(** * Coq Automation *)

(** The amount of repetition in this last proof is a little
    annoying.  And if either the language of arithmetic expressions or
    the optimization being proved sound were significantly more
    complex, it would start to be a real problem.

    So far, we've been doing all our proofs using just a small handful
    of Coq's tactics and completely ignoring its powerful facilities
    for constructing parts of proofs automatically.  This section
    introduces some of these facilities, and we will see more over the
    next several chapters.  Getting used to them will take some
    energy -- Coq's automation is a power tool -- but it will allow us
    to scale up our efforts to more complex definitions and more
    interesting properties without becoming overwhelmed by boring,
    repetitive, low-level details. *)

(* ================================================================= *)
(** ** Tacticals *)

(** _Tacticals_ is Coq's term for tactics that take other tactics as
    arguments -- "higher-order tactics," if you will.  *)

(* ----------------------------------------------------------------- *)
(** *** The [try] Tactical *)

(** If [T] is a tactic, then [try T] is a tactic that is just like [T]
    except that, if [T] fails, [try T] _successfully_ does nothing at
    all (instead of failing). *)

Theorem silly1 : forall ae, aeval ae = aeval ae.
Proof. try reflexivity. (* this just does [reflexivity] *) Qed.

Theorem silly2 : forall (P : Prop), P -> P.
Proof.
  intros P HP.
  try reflexivity. (* just [reflexivity] would have failed *)
  apply HP. (* we can still finish the proof in some other way *)
Qed.

(** There is no real reason to use [try] in completely manual
    proofs like these, but it is very useful for doing automated
    proofs in conjunction with the [;] tactical, which we show
    next. *)

(* ----------------------------------------------------------------- *)
(** *** The [;] Tactical (Simple Form) *)

(** In its most common form, the [;] tactical takes two tactics as
    arguments.  The compound tactic [T;T'] first performs [T] and then
    performs [T'] on _each subgoal_ generated by [T]. *)

(** For example, consider the following trivial lemma: *)

Lemma foo : forall n, leb 0 n = true.
Proof.
  intros.
  destruct n.
    (* Leaves two subgoals, which are discharged identically...  *)
    - (* n=0 *) simpl. reflexivity.
    - (* n=Sn' *) simpl. reflexivity.
Qed.

(** We can simplify this proof using the [;] tactical: *)

Lemma foo' : forall n, leb 0 n = true.
Proof.
  intros.
  (* [destruct] the current goal *)
  destruct n;
  (* then [simpl] each resulting subgoal *)
  simpl;
  (* and do [reflexivity] on each resulting subgoal *)
  reflexivity.
Qed.

(** Using [try] and [;] together, we can get rid of the repetition in
    the proof that was bothering us a little while ago. *)

Theorem optimize_0plus_sound': forall a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a.
  induction a;
    (* Most cases follow directly by the IH... *)
    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).
    (* ... but the remaining cases -- ANum and APlus --
       are different: *)
  - (* ANum *) reflexivity.
  - (* APlus *)
    destruct a1;
      (* Again, most cases follow directly by the IH: *)
      try (simpl; simpl in IHa1; rewrite IHa1;
           rewrite IHa2; reflexivity).
    (* The interesting case, on which the [try...]
       does nothing, is when [e1 = ANum n]. In this
       case, we have to destruct [n] (to see whether
       the optimization applies) and rewrite with the
       induction hypothesis. *)
    + (* a1 = ANum n *) destruct n;
      simpl; rewrite IHa2; reflexivity.   Qed.

(** Coq experts often use this "[...; try... ]" idiom after a tactic
    like [induction] to take care of many similar cases all at once.
    Naturally, this practice has an analog in informal proofs.  For
    example, here is an informal proof of the optimization theorem
    that matches the structure of the formal one:

    _Theorem_: For all arithmetic expressions [a],

       aeval (optimize_0plus a) = aeval a.

    _Proof_: By induction on [a].  Most cases follow directly from the
    IH.  The remaining cases are as follows:

      - Suppose [a = ANum n] for some [n].  We must show

          aeval (optimize_0plus (ANum n)) = aeval (ANum n).

        This is immediate from the definition of [optimize_0plus].

      - Suppose [a = APlus a1 a2] for some [a1] and [a2].  We must
        show

          aeval (optimize_0plus (APlus a1 a2)) = aeval (APlus a1 a2).

        Consider the possible forms of [a1].  For most of them,
        [optimize_0plus] simply calls itself recursively for the
        subexpressions and rebuilds a new expression of the same form
        as [a1]; in these cases, the result follows directly from the
        IH.

        The interesting case is when [a1 = ANum n] for some [n].  If
        [n = 0], then

          optimize_0plus (APlus a1 a2) = optimize_0plus a2

        and the IH for [a2] is exactly what we need.  On the other
        hand, if [n = S n'] for some [n'], then again [optimize_0plus]
        simply calls itself recursively, and the result follows from
        the IH.  [] *)

(** However, this proof can still be improved: the first case (for
    [a = ANum n]) is very trivial -- even more trivial than the cases
    that we said simply followed from the IH -- yet we have chosen to
    write it out in full.  It would be better and clearer to drop it
    and just say, at the top, "Most cases are either immediate or
    direct from the IH.  The only interesting case is the one for
    [APlus]..."  We can make the same improvement in our formal proof
    too.  Here's how it looks: *)

Theorem optimize_0plus_sound'': forall a,
  aeval (optimize_0plus a) = aeval a.
Proof.
  intros a.
  induction a;
    (* Most cases follow directly by the IH *)
    try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
    (* ... or are immediate by definition *)
    try reflexivity.
  (* The interesting case is when a = APlus a1 a2. *)
  - (* APlus *)
    destruct a1; try (simpl; simpl in IHa1; rewrite IHa1;
                      rewrite IHa2; reflexivity).
    + (* a1 = ANum n *) destruct n;
      simpl; rewrite IHa2; reflexivity. Qed.

(* ----------------------------------------------------------------- *)
(** *** The [;] Tactical (General Form) *)

(** The [;] tactical also has a more general form than the simple
    [T;T'] we've seen above.  If [T], [T1], ..., [Tn] are tactics,
    then

      T; [T1 | T2 | ... | Tn]

   is a tactic that first performs [T] and then performs [T1] on the
   first subgoal generated by [T], performs [T2] on the second
   subgoal, etc.

   So [T;T'] is just special notation for the case when all of the
   [Ti]'s are the same tactic; i.e., [T;T'] is shorthand for:

      T; [T' | T' | ... | T']
*)

(* ----------------------------------------------------------------- *)
(** *** The [repeat] Tactical *)

(** The [repeat] tactical takes another tactic and keeps applying this
    tactic until it fails. Here is an example showing that [10] is in
    a long list using repeat. *)

Theorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
  repeat (try (left; reflexivity); right).
Qed.

(** The tactic [repeat T] never fails: if the tactic [T] doesn't apply
    to the original goal, then repeat still succeeds without changing
    the original goal (i.e., it repeats zero times). *)

Theorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].
Proof.
  repeat (left; reflexivity).
  repeat (right; try (left; reflexivity)).
Qed.

(** The tactic [repeat T] also does not have any upper bound on the
    number of times it applies [T].  If [T] is a tactic that always
    succeeds, then repeat [T] will loop forever (e.g., [repeat simpl]
    loops, since [simpl] always succeeds).  While evaluation in Coq's
    term language, Gallina, is guaranteed to terminate, tactic
    evaluation is not!  This does not affect Coq's logical
    consistency, however, since the job of [repeat] and other tactics
    is to guide Coq in constructing proofs; if the construction
    process diverges, this simply means that we have failed to
    construct a proof, not that we have constructed a wrong one. *)

(** **** Exercise: 3 stars (optimize_0plus_b_sound)  *)
(** Since the [optimize_0plus] transformation doesn't change the value
    of [aexp]s, we should be able to apply it to all the [aexp]s that
    appear in a [bexp] without changing the [bexp]'s value.  Write a
    function that performs this transformation on [bexp]s and prove
    it is sound.  Use the tacticals we've just seen to make the proof
    as elegant as possible. *)

Fixpoint optimize_0plus_b (b : bexp) : bexp :=
  match b with
  | BTrue       => BTrue
  | BFalse      => BFalse
  | BEq a1 a2   => BEq (optimize_0plus a1) (optimize_0plus a2)
  | BLe a1 a2   => BLe (optimize_0plus a1) (optimize_0plus a2)
  | BNot b1     => BNot (optimize_0plus_b b1)
  | BAnd b1 b2  => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)
  end.

Theorem optimize_0plus_b_sound : forall b,
  beval (optimize_0plus_b b) = beval b.
Proof.
  intros. induction b;
            repeat (try (simpl; reflexivity));
  repeat (simpl; repeat (rewrite optimize_0plus_sound); reflexivity).
  - simpl. rewrite IHb. reflexivity.
  - simpl. rewrite IHb1. rewrite IHb2. reflexivity.
Qed.

(** [] *)

(** **** Exercise: 4 stars, optional (optimizer)  *)
(** _Design exercise_: The optimization implemented by our
    [optimize_0plus] function is only one of many possible
    optimizations on arithmetic and boolean expressions.  Write a more
    sophisticated optimizer and prove it correct.  (You will probably
    find it easiest to start small -- add just a single, simple
    optimization and prove it correct -- and build up to something
    more interesting incrementially.)

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

(* ================================================================= *)
(** ** Defining New Tactic Notations *)

(** Coq also provides several ways of "programming" tactic
scripts.

    - The [Tactic Notation] idiom illustrated below gives a handy way
      to define "shorthand tactics" that bundle several tactics into a
      single command.

    - For more sophisticated programming, Coq offers a built-in
      language called [Ltac] with primitives that can examine and
      modify the proof state.  The details are a bit too complicated
      to get into here (and it is generally agreed that [Ltac] is not
      the most beautiful part of Coq's design!), but they can be found
      in the reference manual and other books on Coq, and there are
      many examples of [Ltac] definitions in the Coq standard library
      that you can use as examples.

    - There is also an OCaml API, which can be used to build tactics
      that access Coq's internal structures at a lower level, but this
      is seldom worth the trouble for ordinary Coq users.

    The [Tactic Notation] mechanism is the easiest to come to grips
    with, and it offers plenty of power for many purposes.  Here's an
    example. *)

Tactic Notation "simpl_and_try" tactic(c) :=
  simpl;
  try c.

(** This defines a new tactical called [simpl_and_try] that takes one
    tactic [c] as an argument and is defined to be equivalent to the
    tactic [simpl; try c].  Now writing "[simpl_and_try reflexivity.]"
    in a proof will be the same as writing "[simpl; try
    reflexivity.]" *)

(* ================================================================= *)
(** ** The [omega] Tactic *)

(** The [omega] tactic implements a decision procedure for a subset of
    first-order logic called _Presburger arithmetic_.  It is based on
    the Omega algorithm invented by William Pugh [Pugh 1991].

    If the goal is a universally quantified formula made out of

      - numeric constants, addition ([+] and [S]), subtraction ([-]
        and [pred]), and multiplication by constants (this is what
        makes it Presburger arithmetic),

      - equality ([=] and [<>]) and ordering ([<=]), and

      - the logical connectives [/\], [\/], [~], and [->],

    then invoking [omega] will either solve the goal or fail, meaning
    that the goal is actually false.  (If the goal is _not_ of this
    form, [omega] will also fail.) *)

Example silly_presburger_example : forall m n o p,
  m + n <= n + o /\ o + 3 = p + 3 ->
  m <= p.
Proof.
  intros. omega.
Qed.

(** (Note the [Require Import Coq.omega.Omega.] at the top of
    the file.) *)

(* ================================================================= *)
(** ** A Few More Handy Tactics *)

(** Finally, here are some miscellaneous tactics that you may find
    convenient.

     - [clear H]: Delete hypothesis [H] from the context.

     - [subst x]: Find an assumption [x = e] or [e = x] in the
       context, replace [x] with [e] throughout the context and
       current goal, and clear the assumption.

     - [subst]: Substitute away _all_ assumptions of the form [x = e]
       or [e = x].

     - [rename... into...]: Change the name of a hypothesis in the
       proof context.  For example, if the context includes a variable
       named [x], then [rename x into y] will change all occurrences
       of [x] to [y].

     - [assumption]: Try to find a hypothesis [H] in the context that
       exactly matches the goal; if one is found, behave like [apply
       H].

     - [contradiction]: Try to find a hypothesis [H] in the current
       context that is logically equivalent to [False].  If one is
       found, solve the goal.

     - [constructor]: Try to find a constructor [c] (from some
       [Inductive] definition in the current environment) that can be
       applied to solve the current goal.  If one is found, behave
       like [apply c].

    We'll see examples as we go along. *)

(* ################################################################# *)
(** * Evaluation as a Relation *)

(** We have presented [aeval] and [beval] as functions defined by
    [Fixpoint]s.  Another way to think about evaluation -- one that we
    will see is often more flexible -- is as a _relation_ between
    expressions and their values.  This leads naturally to [Inductive]
    definitions like the following one for arithmetic expressions... *)

Module aevalR_first_try.

Inductive aevalR : aexp -> nat -> Prop :=
  | E_ANum  : forall (n: nat),
      aevalR (ANum n) n
  | E_APlus : forall (e1 e2: aexp) (n1 n2: nat),
      aevalR e1 n1 ->
      aevalR e2 n2 ->
      aevalR (APlus e1 e2) (n1 + n2)
  | E_AMinus: forall (e1 e2: aexp) (n1 n2: nat),
      aevalR e1 n1 ->
      aevalR e2 n2 ->
      aevalR (AMinus e1 e2) (n1 - n2)
  | E_AMult : forall (e1 e2: aexp) (n1 n2: nat),
      aevalR e1 n1 ->
      aevalR e2 n2 ->
      aevalR (AMult e1 e2) (n1 * n2).

(** It will be convenient to have an infix notation for
    [aevalR].  We'll write [e \\ n] to mean that arithmetic expression
    [e] evaluates to value [n]. *)

Notation "e '\\' n"
         := (aevalR e n)
            (at level 50, left associativity)
         : type_scope.

End aevalR_first_try.

(** In fact, Coq provides a way to use this notation in the
    definition of [aevalR] itself.  This reduces confusion by avoiding
    situations where we're working on a proof involving statements in
    the form [e \\ n] but we have to refer back to a definition
    written using the form [aevalR e n].

    We do this by first "reserving" the notation, then giving the
    definition together with a declaration of what the notation
    means. *)

Reserved Notation "e '\\' n" (at level 50, left associativity).

Inductive aevalR : aexp -> nat -> Prop :=
  | E_ANum : forall (n:nat),
      (ANum n) \\ n
  | E_APlus : forall (e1 e2: aexp) (n1 n2 : nat),
      (e1 \\ n1) -> (e2 \\ n2) -> (APlus e1 e2) \\ (n1 + n2)
  | E_AMinus : forall (e1 e2: aexp) (n1 n2 : nat),
      (e1 \\ n1) -> (e2 \\ n2) -> (AMinus e1 e2) \\ (n1 - n2)
  | E_AMult :  forall (e1 e2: aexp) (n1 n2 : nat),
      (e1 \\ n1) -> (e2 \\ n2) -> (AMult e1 e2) \\ (n1 * n2)

  where "e '\\' n" := (aevalR e n) : type_scope.

(* ================================================================= *)
(** ** Inference Rule Notation *)

(** In informal discussions, it is convenient to write the rules for
    [aevalR] and similar relations in the more readable graphical form
    of _inference rules_, where the premises above the line justify
    the conclusion below the line (we have already seen them in the
    [IndProp] chapter). *)

(** For example, the constructor [E_APlus]...

      | E_APlus : forall (e1 e2: aexp) (n1 n2: nat),
          aevalR e1 n1 ->
          aevalR e2 n2 ->
          aevalR (APlus e1 e2) (n1 + n2)

    ...would be written like this as an inference rule:

                               e1 \\ n1
                               e2 \\ n2
                         --------------------                         (E_APlus)
                         APlus e1 e2 \\ n1+n2
*)

(** Formally, there is nothing deep about inference rules: they
    are just implications.  You can read the rule name on the right as
    the name of the constructor and read each of the linebreaks
    between the premises above the line (as well as the line itself)
    as [->].  All the variables mentioned in the rule ([e1], [n1],
    etc.) are implicitly bound by universal quantifiers at the
    beginning. (Such variables are often called _metavariables_ to
    distinguish them from the variables of the language we are
    defining.  At the moment, our arithmetic expressions don't include
    variables, but we'll soon be adding them.)  The whole collection
    of rules is understood as being wrapped in an [Inductive]
    declaration.  In informal prose, this is either elided or else
    indicated by saying something like "Let [aevalR] be the smallest
    relation closed under the following rules...". *)

(** For example, [\\] is the smallest relation closed under these
    rules:

                             -----------                               (E_ANum)
                             ANum n \\ n

                               e1 \\ n1
                               e2 \\ n2
                         --------------------                         (E_APlus)
                         APlus e1 e2 \\ n1+n2

                               e1 \\ n1
                               e2 \\ n2
                        ---------------------                        (E_AMinus)
                        AMinus e1 e2 \\ n1-n2

                               e1 \\ n1
                               e2 \\ n2
                         --------------------                         (E_AMult)
                         AMult e1 e2 \\ n1*n2
*)

(* ================================================================= *)
(** ** Equivalence of the Definitions *)

(** It is straightforward to prove that the relational and functional
    definitions of evaluation agree: *)

Theorem aeval_iff_aevalR : forall a n,
  (a \\ n) <-> aeval a = n.
Proof.
 split.
 - (* -> *)
   intros H.
   induction H; simpl.
   + (* E_ANum *)
     reflexivity.
   + (* E_APlus *)
     rewrite IHaevalR1.  rewrite IHaevalR2.  reflexivity.
   + (* E_AMinus *)
     rewrite IHaevalR1.  rewrite IHaevalR2.  reflexivity.
   + (* E_AMult *)
     rewrite IHaevalR1.  rewrite IHaevalR2.  reflexivity.
 - (* <- *)
   generalize dependent n.
   induction a;
      simpl; intros; subst.
   + (* ANum *)
     apply E_ANum.
   + (* APlus *)
     apply E_APlus.
      apply IHa1. reflexivity.
      apply IHa2. reflexivity.
   + (* AMinus *)
     apply E_AMinus.
      apply IHa1. reflexivity.
      apply IHa2. reflexivity.
   + (* AMult *)
     apply E_AMult.
      apply IHa1. reflexivity.
      apply IHa2. reflexivity.
Qed.

(** We can make the proof quite a bit shorter by making more
    use of tacticals. *)

Theorem aeval_iff_aevalR' : forall a n,
  (a \\ n) <-> aeval a = n.
Proof.
  (* WORKED IN CLASS *)
  split.
  - (* -> *)
    intros H; induction H; subst; reflexivity.
  - (* <- *)
    generalize dependent n.
    induction a; simpl; intros; subst; constructor;
       try apply IHa1; try apply IHa2; reflexivity.
Qed.

(** **** Exercise: 3 stars (bevalR)  *)
(** Write a relation [bevalR] in the same style as
    [aevalR], and prove that it is equivalent to [beval].*)

Reserved Notation "e '\\\' n" (at level 50, left associativity).

Inductive bevalR: bexp -> bool -> Prop :=
| E_BTrue : (BTrue \\\ true)
| E_BFalse : (BFalse \\\ false)
| E_BEq : forall (a1 a2 : aexp) (n1 n2 : nat),
    (a1 \\ n1) -> (a2 \\ n2) -> (BEq a1 a2) \\\ (beq_nat n1 n2)
| E_BLe : forall (a1 a2 : aexp) (n1 n2 : nat),
    (a1 \\ n1) -> (a2 \\ n2) -> (BLe a1 a2) \\\ (leb n1 n2)
(* | E_BNot : forall (b : bexp) (b' : bool), *)
(*     (b \\\ b') -> (BNot b) \\\ (negb b') *)
| E_BNot : forall (b : bexp) (b' : bool),
    (bevalR b b') -> bevalR (BNot b) (negb b')

| E_BAnd : forall (b1 b2 : bexp) (b1' b2' : bool),
    (b1 \\\ b1') -> (b2 \\\ b2') -> (BAnd b1 b2) \\\ (andb b1' b2')
where "e '\\\' n" := (bevalR e n) : type_scope .

Lemma beval_iff_bevalR : forall b bv,
  bevalR b bv <-> beval b = bv.
Proof.
  split.
  intros.
  induction H;
    (* Base Cases *)
  (try (simpl; reflexivity));
    (* Arithmetic Inductive Cases *)
  (try (rewrite aeval_iff_aevalR in H;
               rewrite aeval_iff_aevalR in H0;
               rewrite <- H; rewrite <- H0; reflexivity));
  (* The Not case *)
  repeat (try (simpl; rewrite IHbevalR; reflexivity)).
  try (simpl; rewrite IHbevalR1; rewrite IHbevalR2; reflexivity).
  - intros. generalize dependent bv;
    induction b; simpl; intros; subst;
    repeat (try (constructor; apply aeval_iff_aevalR)).
    (* repeat (try (constructor; repeat assumption; reflexivity)). *)
    (* WHY CAN"T WE USE ASSUMPTION HERE ?!?!?!*)
    + constructor. apply IHb. reflexivity.
    + constructor. apply IHb1. reflexivity.
      * apply IHb2. reflexivity. Qed.

(** [] *)

End AExp.

(* ================================================================= *)
(** ** Computational vs. Relational Definitions *)

(** For the definitions of evaluation for arithmetic and boolean
    expressions, the choice of whether to use functional or relational
    definitions is mainly a matter of taste: either way works.

    However, there are circumstances where relational definitions of
    evaluation work much better than functional ones.  *)

Module aevalR_division.

(** For example, suppose that we wanted to extend the arithmetic
    operations by considering also a division operation:*)

Inductive aexp : Type :=
  | ANum : nat -> aexp
  | APlus : aexp -> aexp -> aexp
  | AMinus : aexp -> aexp -> aexp
  | AMult : aexp -> aexp -> aexp
  | ADiv : aexp -> aexp -> aexp.   (* <--- new *)

(** Extending the definition of [aeval] to handle this new operation
    would not be straightforward (what should we return as the result
    of [ADiv (ANum 5) (ANum 0)]?).  But extending [aevalR] is
    straightforward. *)

Reserved Notation "e '\\' n"
                  (at level 50, left associativity).

Inductive aevalR : aexp -> nat -> Prop :=
  | E_ANum : forall (n:nat),
      (ANum n) \\ n
  | E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (APlus a1 a2) \\ (n1 + n2)
  | E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (AMinus a1 a2) \\ (n1 - n2)
  | E_AMult :  forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (AMult a1 a2) \\ (n1 * n2)
  | E_ADiv :  forall (a1 a2: aexp) (n1 n2 n3: nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (n2 > 0) ->
      (mult n2 n3 = n1) -> (ADiv a1 a2) \\ n3

where "a '\\' n" := (aevalR a n) : type_scope.

End aevalR_division.

Module aevalR_extended.

(** Suppose, instead, that we want to extend the arithmetic operations
    by a nondeterministic number generator [any] that, when evaluated,
    may yield any number.  (Note that this is not the same as making a
    _probabilistic_ choice among all possible numbers -- we're not
    specifying any particular distribution of results, but just saying
    what results are _possible_.) *)

Reserved Notation "e '\\' n" (at level 50, left associativity).

Inductive aexp : Type :=
  | AAny  : aexp                   (* <--- NEW *)
  | ANum : nat -> aexp
  | APlus : aexp -> aexp -> aexp
  | AMinus : aexp -> aexp -> aexp
  | AMult : aexp -> aexp -> aexp.

(** Again, extending [aeval] would be tricky, since now evaluation is
    _not_ a deterministic function from expressions to numbers, but
    extending [aevalR] is no problem... *)

Inductive aevalR : aexp -> nat -> Prop :=
  | E_Any : forall (n:nat),
      AAny \\ n                 (* <--- new *)
  | E_ANum : forall (n:nat),
      (ANum n) \\ n
  | E_APlus : forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (APlus a1 a2) \\ (n1 + n2)
  | E_AMinus : forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (AMinus a1 a2) \\ (n1 - n2)
  | E_AMult :  forall (a1 a2: aexp) (n1 n2 : nat),
      (a1 \\ n1) -> (a2 \\ n2) -> (AMult a1 a2) \\ (n1 * n2)

where "a '\\' n" := (aevalR a n) : type_scope.

End aevalR_extended.

(** At this point you maybe wondering: which style should I use by
    default?  The examples above show that relational definitions are
    fundamentally more powerful than functional ones.  For situations
    like these, where the thing being defined is not easy to express
    as a function, or indeed where it is _not_ a function, there is no
    choice.  But what about when both styles are workable?

    One point in favor of relational definitions is that they can be
    more elegant and easier to understand.

    Another is that Coq automatically generates nice inversion and
    induction principles from [Inductive] definitions. *)

(** On the other hand, functional definitions can often be more
    convenient:
     - Functions are by definition deterministic and defined on all
       arguments; for a relation we have to show these properties
       explicitly if we need them.
     - With functions we can also take advantage of Coq's computation
       mechanism to simplify expressions during proofs.

    Furthermore, functions can be directly "extracted" to executable
    code in OCaml or Haskell. *)

(** Ultimately, the choice often comes down to either the specifics of
    a particular situation or simply a question of taste.  Indeed, in
    large Coq developments it is common to see a definition given in
    _both_ functional and relational styles, plus a lemma stating that
    the two coincide, allowing further proofs to switch from one point
    of view to the other at will.*)

(* ################################################################# *)
(** * Expressions With Variables *)

(** Let's turn our attention back to defining Imp.  The next thing we
    need to do is to enrich our arithmetic and boolean expressions
    with variables.  To keep things simple, we'll assume that all
    variables are global and that they only hold numbers. *)

(* ================================================================= *)
(** ** States *)

(** Since we'll want to look variables up to find out their current
    values, we'll reuse maps from the [Maps] chapter, with
    [string]s as the type of variables in Imp.

    A _machine state_ (or just _state_) represents the current values
    of _all_ variables at some point in the execution of a program. *)

(** For simplicity, we assume that the state is defined for
    _all_ variables, even though any given program is only going to
    mention a finite number of them.  The state captures all of the
    information stored in memory.  For Imp programs, because each
    variable stores a natural number, we can represent the state as a
    mapping from strings to [nat], and will use [0] as default value
    in the store. For more complex programming languages, the state
    might have more structure. *)

Definition state := total_map nat.

(* ================================================================= *)
(** ** Syntax  *)

(** We can add variables to the arithmetic expressions we had before by
    simply adding one more constructor: *)

Inductive aexp : Type :=
  | ANum : nat -> aexp
  | AId : string -> aexp                (* <----- NEW *)
  | APlus : aexp -> aexp -> aexp
  | AMinus : aexp -> aexp -> aexp
  | AMult : aexp -> aexp -> aexp.

(** Defining a few variable names as notational shorthands will make
    examples easier to read: *)

Definition W : string := "W".
Definition X : string := "X".
Definition Y : string := "Y".
Definition Z : string := "Z".

(** (This convention for naming program variables ([X], [Y],
    [Z]) clashes a bit with our earlier use of uppercase letters for
    types.  Since we're not using polymorphism heavily in the chapters
    developed to Imp, this overloading should not cause confusion.) *)

(** The definition of [bexp]s is unchanged (except that it now refers
    to the new [aexp]s): *)

Inductive bexp : Type :=
  | BTrue : bexp
  | BFalse : bexp
  | BEq : aexp -> aexp -> bexp
  | BLe : aexp -> aexp -> bexp
  | BNot : bexp -> bexp
  | BAnd : bexp -> bexp -> bexp.

(* ================================================================= *)
(** ** Notations *)
(** To make Imp programs easier to read and write, we introduce some
    notations and implicit coercions.

    You do not need to understand what these declarations do in detail
    to follow this chapter.  Briefly, though, the [Coercion]
    declaration in Coq stipulates that a function (or constructor) can
    be implicitly used by the type system to coerce a value of the
    input type to a value of the output type.  For instance, the
    coercion declaration for [AId] allows us to use plain strings when
    an [aexp] is expected; the string will implicitly be wrapped with
    [AId]. *)

(** The notations below are declared in specific _notation scopes_, in
    order to avoid conflicts with other interpretations of the same
    symbols.  Again, it is not necessary to understand the details. *)

Coercion AId : string >-> aexp.
Coercion ANum : nat >-> aexp.
Definition bool_to_bexp (b: bool) : bexp :=
  if b then BTrue else BFalse.
Coercion bool_to_bexp : bool >-> bexp.

Bind Scope aexp_scope with aexp.
Infix "+" := APlus : aexp_scope.
Infix "-" := AMinus : aexp_scope.
Infix "*" := AMult : aexp_scope.
Bind Scope bexp_scope with bexp.
Infix "<=" := BLe : bexp_scope.
Infix "=" := BEq : bexp_scope.
Infix "&&" := BAnd : bexp_scope.
Notation "'!' b" := (BNot b) (at level 60) : bexp_scope.

(** We can now write [3 + (X * 2)] instead  of [APlus 3 (AMult X 2)],
    and [true && !(X <= 4)] instead of [BAnd true (BNot (BLe X 4))]. *)

(* ================================================================= *)
(** ** Evaluation *)

(** The arith and boolean evaluators are extended to handle
    variables in the obvious way, taking a state as an extra
    argument: *)

Fixpoint aeval (st : state) (a : aexp) : nat :=
  match a with
  | ANum n => n
  | AId x => st x                                (* <----- NEW *)
  | APlus a1 a2 => (aeval st a1) + (aeval st a2)
  | AMinus a1 a2  => (aeval st a1) - (aeval st a2)
  | AMult a1 a2 => (aeval st a1) * (aeval st a2)
  end.

Fixpoint beval (st : state) (b : bexp) : bool :=
  match b with
  | BTrue       => true
  | BFalse      => false
  | BEq a1 a2   => beq_nat (aeval st a1) (aeval st a2)
  | BLe a1 a2   => leb (aeval st a1) (aeval st a2)
  | BNot b1     => negb (beval st b1)
  | BAnd b1 b2  => andb (beval st b1) (beval st b2)
  end.

(** We specialize our notation for total maps to the specific case of states,
    i.e. using [{ --> 0 }] as empty state. *)

Notation "{ a --> x }" :=
  (t_update { --> 0 } a x) (at level 0).
Notation "{ a --> x ; b --> y }" :=
  (t_update ({ a --> x }) b y) (at level 0).
Notation "{ a --> x ; b --> y ; c --> z }" :=
  (t_update ({ a --> x ; b --> y }) c z) (at level 0).
Notation "{ a --> x ; b --> y ; c --> z ; d --> t }" :=
    (t_update ({ a --> x ; b --> y ; c --> z }) d t) (at level 0).
Notation "{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }" :=
  (t_update ({ a --> x ; b --> y ; c --> z ; d --> t }) e u) (at level 0).
Notation "{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u ; f --> v }" :=
  (t_update ({ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }) f v) (at level 0).

Example aexp1 :
  aeval { X --> 5 } (3 + (X * 2))
  = 13.
Proof. reflexivity. Qed.

Example bexp1 :
  beval { X --> 5 } (true && !(X <= 4))
  = true.
Proof. reflexivity. Qed.

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

(** Now we are ready define the syntax and behavior of Imp
    _commands_ (sometimes called _statements_). *)

(* ================================================================= *)
(** ** Syntax *)

(** Informally, commands [c] are described by the following BNF
    grammar.  (We choose this slightly awkward concrete syntax for the
    sake of being able to define Imp syntax using Coq's Notation
    mechanism.  In particular, we use [IFB] to avoid conflicting with
    the [if] notation from the standard library.)

     c ::= SKIP | x ::= a | c ;; c | IFB b THEN c ELSE c FI
         | WHILE b DO c END
*)
(**
    For example, here's factorial in Imp:

     Z ::= X;;
     Y ::= 1;;
     WHILE ! (Z = 0) DO
       Y ::= Y * Z;;
       Z ::= Z - 1
     END

   When this command terminates, the variable [Y] will contain the
   factorial of the initial value of [X]. *)

(** Here is the formal definition of the abstract syntax of
    commands: *)

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

(** As for expressions, we can use a few [Notation] declarations to make
    reading and writing Imp programs more convenient. *)

Bind Scope com_scope with com.
Notation "'SKIP'" :=
   CSkip : com_scope.
Notation "x '::=' a" :=
  (CAss x a) (at level 60) : com_scope.
Notation "c1 ;; c2" :=
  (CSeq c1 c2) (at level 80, right associativity) : com_scope.
Notation "'WHILE' b 'DO' c 'END'" :=
  (CWhile b c) (at level 80, right associativity) : com_scope.
Notation "'IFB' c1 'THEN' c2 'ELSE' c3 'FI'" :=
  (CIf c1 c2 c3) (at level 80, right associativity) : com_scope.

(** The following declaration is needed to be able to use the
    notations in match patterns. *)
Open Scope com_scope.

(** For example, here is the factorial function again, written as a
    formal definition to Coq: *)

Definition fact_in_coq : com :=
  Z ::= X;;
  Y ::= 1;;
  WHILE ! (Z = 0) DO
    Y ::= Y * Z;;
    Z ::= Z - 1
  END.

(* ================================================================= *)
(** ** More Examples *)

(** Assignment: *)

Definition plus2 : com :=
  X ::= X + 2.

Definition XtimesYinZ : com :=
  Z ::= X * Y.

Definition subtract_slowly_body : com :=
  Z ::= Z - 1 ;;
  X ::= X - 1.

(* ----------------------------------------------------------------- *)
(** *** Loops *)

Definition subtract_slowly : com :=
  WHILE ! (X = 0) DO
    subtract_slowly_body
  END.

Definition subtract_3_from_5_slowly : com :=
  X ::= 3 ;;
  Z ::= 5 ;;
  subtract_slowly.

(* ----------------------------------------------------------------- *)
(** *** An infinite loop: *)

Definition loop : com :=
  WHILE true DO
    SKIP
  END.

(* ################################################################# *)
(** * Evaluating Commands *)

(** Next we need to define what it means to evaluate an Imp command.
    The fact that [WHILE] loops don't necessarily terminate makes
    defining an evaluation function tricky... *)

(* ================================================================= *)
(** ** Evaluation as a Function (Failed Attempt) *)

(** Here's an attempt at defining an evaluation function for commands,
    omitting the [WHILE] case. *)

Fixpoint ceval_fun_no_while (st : state) (c : com)
                          : state :=
  match c with
    | SKIP =>
        st
    | x ::= a1 =>
        st & { x --> (aeval st a1) }
    | c1 ;; c2 =>
        let st' := ceval_fun_no_while st c1 in
        ceval_fun_no_while st' c2
    | IFB b THEN c1 ELSE c2 FI =>
        if (beval st b)
          then ceval_fun_no_while st c1
          else ceval_fun_no_while st c2
    | WHILE b DO c END =>
        st  (* bogus *)
  end.

(** In a traditional functional programming language like OCaml or
    Haskell we could add the [WHILE] case as follows:

        Fixpoint ceval_fun (st : state) (c : com) : state :=
          match c with
            ...
            | WHILE b DO c END =>
                if (beval st b)
                  then ceval_fun st (c; WHILE b DO c END)
                  else st
          end.

    Coq doesn't accept such a definition ("Error: Cannot guess
    decreasing argument of fix") because the function we want to
    define is not guaranteed to terminate. Indeed, it _doesn't_ always
    terminate: for example, the full version of the [ceval_fun]
    function applied to the [loop] program above would never
    terminate. Since Coq is not just a functional programming
    language but also a consistent logic, any potentially
    non-terminating function needs to be rejected. Here is
    an (invalid!) program showing what would go wrong if Coq
    allowed non-terminating recursive functions:

         Fixpoint loop_false (n : nat) : False := loop_false n.

    That is, propositions like [False] would become provable
    ([loop_false 0] would be a proof of [False]), which
    would be a disaster for Coq's logical consistency.

    Thus, because it doesn't terminate on all inputs,
    of [ceval_fun] cannot be written in Coq -- at least not without
    additional tricks and workarounds (see chapter [ImpCEvalFun]
    if you're curious about what those might be). *)

(* ================================================================= *)
(** ** Evaluation as a Relation *)

(** Here's a better way: define [ceval] as a _relation_ rather than a
    _function_ -- i.e., define it in [Prop] instead of [Type], as we
    did for [aevalR] above. *)

(** This is an important change.  Besides freeing us from awkward
    workarounds, it gives us a lot more flexibility in the definition.
    For example, if we add nondeterministic features like [any] to the
    language, we want the definition of evaluation to be
    nondeterministic -- i.e., not only will it not be total, it will
    not even be a function! *)

(** We'll use the notation [c / st \\ st'] for the [ceval] relation:
    [c / st \\ st'] means that executing program [c] in a starting
    state [st] results in an ending state [st'].  This can be
    pronounced "[c] takes state [st] to [st']". *)

(* ----------------------------------------------------------------- *)
(** *** Operational Semantics *)

(** Here is an informal definition of evaluation, presented as inference
    rules for readability:

                           ----------------                            (E_Skip)
                           SKIP / st \\ st

                           aeval st a1 = n
                   --------------------------------                     (E_Ass)
                   x := a1 / st \\ st & { x --> n }

                           c1 / st \\ st'
                          c2 / st' \\ st''
                         -------------------                            (E_Seq)
                         c1;;c2 / st \\ st''

                          beval st b1 = true
                           c1 / st \\ st'
                -------------------------------------                (E_IfTrue)
                IF b1 THEN c1 ELSE c2 FI / st \\ st'

                         beval st b1 = false
                           c2 / st \\ st'
                -------------------------------------               (E_IfFalse)
                IF b1 THEN c1 ELSE c2 FI / st \\ st'

                         beval st b = false
                    ------------------------------               (E_WhileFalse)
                    WHILE b DO c END / st \\ st

                          beval st b = true
                           c / st \\ st'
                  WHILE b DO c END / st' \\ st''
                  ---------------------------------               (E_WhileTrue)
                    WHILE b DO c END / st \\ st''
*)

(** Here is the formal definition.  Make sure you understand
    how it corresponds to the inference rules. *)

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

Inductive ceval : com -> state -> state -> Prop :=
  | E_Skip : forall st,
      SKIP / st \\ st
  | E_Ass  : forall st a1 n x,
      aeval st a1 = n ->
      (x ::= a1) / st \\ st & { x --> n }
  | E_Seq : forall c1 c2 st st' st'',
      c1 / st  \\ st' ->
      c2 / st' \\ st'' ->
      (c1 ;; c2) / st \\ st''
  | E_IfTrue : forall st st' b c1 c2,
      beval st b = true ->
      c1 / st \\ st' ->
      (IFB b THEN c1 ELSE c2 FI) / st \\ st'
  | E_IfFalse : forall st st' b c1 c2,
      beval st b = false ->
      c2 / st \\ st' ->
      (IFB b THEN c1 ELSE c2 FI) / st \\ st'
  | E_WhileFalse : forall b st c,
      beval st b = false ->
      (WHILE b DO c END) / st \\ st
  | E_WhileTrue : forall st st' st'' b c,
      beval st b = true ->
      c / st \\ st' ->
      (WHILE b DO c END) / st' \\ st'' ->
      (WHILE b DO c END) / st \\ st''

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

(** The cost of defining evaluation as a relation instead of a
    function is that we now need to construct _proofs_ that some
    program evaluates to some result state, rather than just letting
    Coq's computation mechanism do it for us. *)

Example ceval_example1:
    (X ::= 2;;
     IFB X <= 1
       THEN Y ::= 3
       ELSE Z ::= 4
     FI)
   / { --> 0 } \\ { X --> 2 ; Z --> 4 }.
Proof.
  (* We must supply the intermediate state *)
  apply E_Seq with { X --> 2 }.
  - (* assignment command *)
    apply E_Ass. reflexivity.
  - (* if command *)
    apply E_IfFalse.
      reflexivity.
      apply E_Ass. reflexivity.  Qed.

(** **** Exercise: 2 stars (ceval_example2)  *)
Example ceval_example2:
  (X ::= 0;; Y ::= 1;; Z ::= 2) / { --> 0 } \\
  { X --> 0 ; Y --> 1 ; Z --> 2 }.
Proof.
  apply E_Seq with { X --> 0}.
  - apply E_Ass. simpl. reflexivity.
  - apply E_Seq with { X --> 0; Y --> 1}.
    + apply E_Ass. simpl. reflexivity.
    + apply E_Ass. simpl. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (pup_to_n)  *)
(** Write an Imp program that sums the numbers from [1] to
   [X] (inclusive: [1 + 2 + ... + X]) in the variable [Y].
   Prove that this program executes as intended for [X] = [2]
   (this is trickier than you might expect). *)

Definition pup_to_n : com
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Theorem pup_to_2_ceval :
  pup_to_n / { X --> 2 }
     \\ { X --> 2 ; Y --> 0 ; Y --> 2 ; X --> 1 ; Y --> 3 ; X --> 0 }.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** Determinism of Evaluation *)

(** Changing from a computational to a relational definition of
    evaluation is a good move because it frees us from the artificial
    requirement that evaluation should be a total function.  But it
    also raises a question: Is the second definition of evaluation
    really a partial function?  Or is it possible that, beginning from
    the same state [st], we could evaluate some command [c] in
    different ways to reach two different output states [st'] and
    [st'']?

    In fact, this cannot happen: [ceval] _is_ a partial function: *)

Theorem ceval_deterministic: forall c st st1 st2,
     c / st \\ st1  ->
     c / st \\ st2 ->
     st1 = st2.
Proof.
  intros c st st1 st2 E1 E2.
  generalize dependent st2.
  induction E1;
           intros st2 E2; inversion E2; subst.
  - (* E_Skip *) reflexivity.
  - (* E_Ass *) reflexivity.
  - (* E_Seq *)
    assert (st' = st'0) as EQ1.
    { (* Proof of assertion *) apply IHE1_1; assumption. }
    subst st'0.
    apply IHE1_2. assumption.
  - (* E_IfTrue, b1 evaluates to true *)
      apply IHE1. assumption.
  - (* E_IfTrue,  b1 evaluates to false (contradiction) *)
      rewrite H in H5. inversion H5.
  - (* E_IfFalse, b1 evaluates to true (contradiction) *)
    rewrite H in H5. inversion H5.
  - (* E_IfFalse, b1 evaluates to false *)
      apply IHE1. assumption.
  - (* E_WhileFalse, b1 evaluates to false *)
    reflexivity.
  - (* E_WhileFalse, b1 evaluates to true (contradiction) *)
    rewrite H in H2. inversion H2.
  - (* E_WhileTrue, b1 evaluates to false (contradiction) *)
    rewrite H in H4. inversion H4.
  - (* E_WhileTrue, b1 evaluates to true *)
      assert (st' = st'0) as EQ1.
      { (* Proof of assertion *) apply IHE1_1; assumption. }
      subst st'0.
      apply IHE1_2. assumption.  Qed.

(* ################################################################# *)
(** * Reasoning About Imp Programs *)

(** We'll get deeper into systematic techniques for reasoning about
    Imp programs in _Programming Language Foundations_, but we can do
    quite a bit just working with the bare definitions.  This section
    explores some examples. *)

Theorem plus2_spec : forall st n st',
  st X = n ->
  plus2 / st \\ st' ->
  st' X = (n + 2).
Proof.
  intros st n st' HX Heval.

  (** Inverting [Heval] essentially forces Coq to expand one step of
      the [ceval] computation -- in this case revealing that [st']
      must be [st] extended with the new value of [X], since [plus2]
      is an assignment *)

  inversion Heval. subst. clear Heval. simpl.
  apply t_update_eq.  Qed.

(** **** Exercise: 3 stars, recommended (XtimesYinZ_spec)  *)
(** State and prove a specification of [XtimesYinZ]. *)

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

(** **** Exercise: 3 stars, recommended (loop_never_stops)  *)
Theorem loop_never_stops : forall st st',
  ~(loop / st \\ st').
Proof.
  intros st st' contra. unfold loop in contra.
  remember (WHILE true DO SKIP END) as loopdef
           eqn:Heqloopdef.

  (** Proceed by induction on the assumed derivation showing that
      [loopdef] terminates.  Most of the cases are immediately
      contradictory (and so can be solved in one step with
      [inversion]). *)

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

(** **** Exercise: 3 stars (no_whiles_eqv)  *)
(** Consider the following function: *)

Fixpoint no_whiles (c : com) : bool :=
  match c with
  | SKIP =>
      true
  | _ ::= _ =>
      true
  | c1 ;; c2 =>
      andb (no_whiles c1) (no_whiles c2)
  | IFB _ THEN ct ELSE cf FI =>
      andb (no_whiles ct) (no_whiles cf)
  | WHILE _ DO _ END  =>
      false
  end.

(** This predicate yields [true] just on programs that have no while
    loops.  Using [Inductive], write a property [no_whilesR] such that
    [no_whilesR c] is provable exactly when [c] is a program with no
    while loops.  Then prove its equivalence with [no_whiles]. *)

Inductive no_whilesR: com -> Prop :=
 (* FILL IN HERE *)
.

Theorem no_whiles_eqv:
   forall c, no_whiles c = true <-> no_whilesR c.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars (no_whiles_terminating)  *)
(** Imp programs that don't involve while loops always terminate.
    State and prove a theorem [no_whiles_terminating] that says this. *)
(** Use either [no_whiles] or [no_whilesR], as you prefer. *)

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

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

(** **** Exercise: 3 stars (stack_compiler)  *)
(** Old HP Calculators, programming languages like Forth and Postscript,
    and abstract machines like the Java Virtual Machine all evaluate
    arithmetic expressions using a _stack_. For instance, the expression

      (2*3)+(3*(4-2))

   would be written as

      2 3 * 3 4 2 - * +

   and evaluated like this (where we show the program being evaluated
   on the right and the contents of the stack on the left):

      [ ]           |    2 3 * 3 4 2 - * +
      [2]           |    3 * 3 4 2 - * +
      [3, 2]        |    * 3 4 2 - * +
      [6]           |    3 4 2 - * +
      [3, 6]        |    4 2 - * +
      [4, 3, 6]     |    2 - * +
      [2, 4, 3, 6]  |    - * +
      [2, 3, 6]     |    * +
      [6, 6]        |    +
      [12]          |

  The goal of this exercise is to write a small compiler that
  translates [aexp]s into stack machine instructions.

  The instruction set for our stack language will consist of the
  following instructions:
     - [SPush n]: Push the number [n] on the stack.
     - [SLoad x]: Load the identifier [x] from the store and push it
                  on the stack
     - [SPlus]:   Pop the two top numbers from the stack, add them, and
                  push the result onto the stack.
     - [SMinus]:  Similar, but subtract.
     - [SMult]:   Similar, but multiply. *)

Inductive sinstr : Type :=
| SPush : nat -> sinstr
| SLoad : string -> sinstr
| SPlus : sinstr
| SMinus : sinstr
| SMult : sinstr.

(** Write a function to evaluate programs in the stack language. It
    should take as input a state, a stack represented as a list of
    numbers (top stack item is the head of the list), and a program
    represented as a list of instructions, and it should return the
    stack after executing the program.  Test your function on the
    examples below.

    Note that the specification leaves unspecified what to do when
    encountering an [SPlus], [SMinus], or [SMult] instruction if the
    stack contains less than two elements.  In a sense, it is
    immaterial what we do, since our compiler will never emit such a
    malformed program. *)

Fixpoint s_execute (st : state) (stack : list nat)
                   (prog : list sinstr)
                 : list nat
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example s_execute1 :
     s_execute { --> 0 } []
       [SPush 5; SPush 3; SPush 1; SMinus]
   = [2; 5].
(* FILL IN HERE *) Admitted.
(* GRADE_THEOREM 0.5: s_execute1 *)

Example s_execute2 :
     s_execute { X --> 3 } [3;4]
       [SPush 4; SLoad X; SMult; SPlus]
   = [15; 4].
(* FILL IN HERE *) Admitted.
(* GRADE_THEOREM 0.5: s_execute2 *)

(** Next, write a function that compiles an [aexp] into a stack
    machine program. The effect of running the program should be the
    same as pushing the value of the expression on the stack. *)

Fixpoint s_compile (e : aexp) : list sinstr
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

(** After you've defined [s_compile], prove the following to test
    that it works. *)

Example s_compile1 :
  s_compile (X - (2 * Y))
  = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced (stack_compiler_correct)  *)
(** Now we'll prove the correctness of the compiler implemented in the
    previous exercise.  Remember that the specification left
    unspecified what to do when encountering an [SPlus], [SMinus], or
    [SMult] instruction if the stack contains less than two
    elements.  (In order to make your correctness proof easier you
    might find it helpful to go back and change your implementation!)

    Prove the following theorem.  You will need to start by stating a
    more general lemma to get a usable induction hypothesis; the main
    theorem will then be a simple corollary of this lemma. *)

Theorem s_compile_correct : forall (st : state) (e : aexp),
  s_execute st [] (s_compile e) = [ aeval st e ].
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (short_circuit)  *)
(** Most modern programming languages use a "short-circuit" evaluation
    rule for boolean [and]: to evaluate [BAnd b1 b2], first evaluate
    [b1].  If it evaluates to [false], then the entire [BAnd]
    expression evaluates to [false] immediately, without evaluating
    [b2].  Otherwise, [b2] is evaluated to determine the result of the
    [BAnd] expression.

    Write an alternate version of [beval] that performs short-circuit
    evaluation of [BAnd] in this manner, and prove that it is
    equivalent to [beval]. *)

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

Module BreakImp.
(** **** Exercise: 4 stars, advanced (break_imp)  *)
(** Imperative languages like C and Java often include a [break] or
    similar statement for interrupting the execution of loops. In this
    exercise we consider how to add [break] to Imp.  First, we need to
    enrich the language of commands with an additional case. *)

Inductive com : Type :=
  | CSkip : com
  | CBreak : com               (* <-- new *)
  | CAss : string -> aexp -> com
  | CSeq : com -> com -> com
  | CIf : bexp -> com -> com -> com
  | CWhile : bexp -> com -> com.

Notation "'SKIP'" :=
  CSkip.
Notation "'BREAK'" :=
  CBreak.
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' c1 'THEN' c2 'ELSE' c3 'FI'" :=
  (CIf c1 c2 c3) (at level 80, right associativity).

(** Next, we need to define the behavior of [BREAK].  Informally,
    whenever [BREAK] is executed in a sequence of commands, it stops
    the execution of that sequence and signals that the innermost
    enclosing loop should terminate.  (If there aren't any
    enclosing loops, then the whole program simply terminates.)  The
    final state should be the same as the one in which the [BREAK]
    statement was executed.

    One important point is what to do when there are multiple loops
    enclosing a given [BREAK]. In those cases, [BREAK] should only
    terminate the _innermost_ loop. Thus, after executing the
    following...

       X ::= 0;;
       Y ::= 1;;
       WHILE 0 <> Y DO
         WHILE TRUE DO
           BREAK
         END;;
         X ::= 1;;
         Y ::= Y - 1
       END

    ... the value of [X] should be [1], and not [0].

    One way of expressing this behavior is to add another parameter to
    the evaluation relation that specifies whether evaluation of a
    command executes a [BREAK] statement: *)

Inductive result : Type :=
  | SContinue : result
  | SBreak : result.

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

(** Intuitively, [c / st \\ s / st'] means that, if [c] is started in
    state [st], then it terminates in state [st'] and either signals
    that the innermost surrounding loop (or the whole program) should
    exit immediately ([s = SBreak]) or that execution should continue
    normally ([s = SContinue]).

    The definition of the "[c / st \\ s / st']" relation is very
    similar to the one we gave above for the regular evaluation
    relation ([c / st \\ st']) -- we just need to handle the
    termination signals appropriately:

    - If the command is [SKIP], then the state doesn't change and
      execution of any enclosing loop can continue normally.

    - If the command is [BREAK], the state stays unchanged but we
      signal a [SBreak].

    - If the command is an assignment, then we update the binding for
      that variable in the state accordingly and signal that execution
      can continue normally.

    - If the command is of the form [IFB b THEN c1 ELSE c2 FI], then
      the state is updated as in the original semantics of Imp, except
      that we also propagate the signal from the execution of
      whichever branch was taken.

    - If the command is a sequence [c1 ;; c2], we first execute
      [c1].  If this yields a [SBreak], we skip the execution of [c2]
      and propagate the [SBreak] signal to the surrounding context;
      the resulting state is the same as the one obtained by
      executing [c1] alone. Otherwise, we execute [c2] on the state
      obtained after executing [c1], and propagate the signal
      generated there.

    - Finally, for a loop of the form [WHILE b DO c END], the
      semantics is almost the same as before. The only difference is
      that, when [b] evaluates to true, we execute [c] and check the
      signal that it raises.  If that signal is [SContinue], then the
      execution proceeds as in the original semantics. Otherwise, we
      stop the execution of the loop, and the resulting state is the
      same as the one resulting from the execution of the current
      iteration.  In either case, since [BREAK] only terminates the
      innermost loop, [WHILE] signals [SContinue]. *)

(** Based on the above description, complete the definition of the
    [ceval] relation. *)

Inductive ceval : com -> state -> result -> state -> Prop :=
  | E_Skip : forall st,
      CSkip / st \\ SContinue / st
  (* FILL IN HERE *)

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

(** Now prove the following properties of your definition of [ceval]: *)

Theorem break_ignore : forall c st st' s,
     (BREAK;; c) / st \\ s / st' ->
     st = st'.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem while_continue : forall b c st st' s,
  (WHILE b DO c END) / st \\ s / st' ->
  s = SContinue.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem while_stops_on_break : forall b c st st',
  beval st b = true ->
  c / st \\ SBreak / st' ->
  (WHILE b DO c END) / st \\ SContinue / st'.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (while_break_true)  *)
Theorem while_break_true : forall b c st st',
  (WHILE b DO c END) / st \\ SContinue / st' ->
  beval st' b = true ->
  exists st'', c / st'' \\ SBreak / st'.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced, optional (ceval_deterministic)  *)
Theorem ceval_deterministic: forall (c:com) st st1 st2 s1 s2,
     c / st \\ s1 / st1  ->
     c / st \\ s2 / st2 ->
     st1 = st2 /\ s1 = s2.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)
End BreakImp.

(** **** Exercise: 4 stars, optional (add_for_loop)  *)
(** Add C-style [for] loops to the language of commands, update the
    [ceval] definition to define the semantics of [for] loops, and add
    cases for [for] loops as needed so that all the proofs in this
    file are accepted by Coq.

    A [for] loop should be parameterized by (a) a statement executed
    initially, (b) a test that is run on each iteration of the loop to
    determine whether the loop should continue, (c) a statement
    executed at the end of each loop iteration, and (d) a statement
    that makes up the body of the loop.  (You don't need to worry
    about making up a concrete Notation for [for] loops, but feel free
    to play with this too if you like.) *)

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


(*|
#############################################################
Is it possible to declare type-dependent ``Notation`` in Coq?
#############################################################

:Link: https://stackoverflow.com/q/69944163
|*)

(*|
Question
********

As Coq has a powerful type inference algorithm, I am wondering whether
we can "overload" notations for different rewriting based on the
``Notation``'s variables.

As an example, I will borrow a piece of my work on formalizing a typed
language's semantics in Coq. In this formalization, I have both pairs
of types and pairs of expressions, and I would like to use the same
symbol for their respective constructor: ``{ _ , _ }``.

.. code-block:: coq

    Inductive type : Type := ... | tpair: type -> type -> type | ...
    Inductive expr : Type := ... | epair: expr -> expr -> expr | ...

    Notation "{ t1 , t2 }" := tpair t1 t2
    Notation "{ e1 , e2 }" := epair e1 e2

I know the last statement will raise an error because of the notation
being already defined; I would appreciate if somebody has thought
about trickery around it, or if there is another "official" way of
doing this.
|*)

(*|
Answer
******

One easy way to overload notations is by using scopes. In fact you
should use scopes most of the time so that your notations don't mix
with notations from other work that you might include or that might
include yours.

Using scope delimiters, you could have ``{ t1 , t2 }%ty`` and ``{ e1 ,
e2 }%exp`` for instance (with the delimiters ``ty`` and ``exp`` to
disambiguate).

That said, in order to leverage typing information, there is one trick
involving typeclasses which is to have a generic notion of pairs which
comes with its own notation, and then declaring instances of that. See
example below:
|*)

Class PairNotation (A : Type) := __pair : A -> A -> A.

Notation "{ x , y }" := (__pair x y).

Instance PairNotationNat : PairNotation nat := {
    __pair n m := n + m
  }.

Axiom term : Type.
Axiom tpair : term -> term -> term.

Instance PairNotationTerm : PairNotation term := {
    __pair := tpair
  }.

Definition foo (n m : nat) : nat := { n , m }.
Definition bar (u v : term) := { u , v }.

(*|
----

**A:** For instance, `the stdpp library
<https://gitlab.mpi-sws.org/iris/stdpp>`__ makes pervasive use of
for-notation-only typeclasses to provide overloaded notations like `≡
(Equiv)
<https://gitlab.mpi-sws.org/iris/stdpp/-/blob/0939f35/theories/base.v#L245-268>`__,
``∅`` (``Empty``), ``_ !! _`` (``Lookup``), etc. A minor naming issue
(this answer does it better than stdpp) is that with a typeclass named
``Equiv`` you might think you have the mathematical properties of an
equivalence relation, whereas all you get is a notation
(well-formedness properties are stated by another typeclass,
``Equivalence``).
|*)


(* Imports *)
From Coq Require Import Arith.EqNat.
From Coq Require Import MSets.
Import ListNotations.
Require Import List.
Require Import lang_spec.
Require Import VarSet.
Require Import lang_ops.

Inductive Judgement : Type :=
| judge (v : var) (t : type)
.

Definition ty_ctx := (list Judgement).

(* Functions to convert between the different types listed above *)

Fixpoint bound_variables (g : ty_ctx) : VarSet.t :=
  match g with
  | nil => VarSet.empty
  | cons (judge v _) g' => VarSet.union (VarSet.singleton v) (bound_variables g')
  end.
Coercion bound_variables : ty_ctx >-> VarSet.t.

Definition ctxu (g1 g2 : ty_ctx) := g1 ++ g2.
Definition ctx_union (g1 g2 : ty_ctx) (disjoint_proof : disj_vars g1 g2) : ty_ctx
  := ctxu g1 g2.

Fixpoint coerce_judgement_to_ty_ctx (j : Judgement) : ty_ctx :=
  cons j nil.
Coercion coerce_judgement_to_ty_ctx : Judgement >-> ty_ctx.

Fixpoint eq (n m : nat) : bool :=
  match n, m with
  | O, O => true
  | S n', S m' => eq n' m'
  | _, _ => false
  end.

Fixpoint restrict_ty_ctx (g : ty_ctx) (x : var) : ty_ctx :=
  match g with
  | nil => nil
  | cons (judge v t) g' => if (eq x v)
                           then (restrict_ty_ctx g' x)
                           else (cons (judge v t) (restrict_ty_ctx g' x))
  end.

Notation "g -- x" := (restrict_ty_ctx g x) (at level 71, left associativity).

Theorem restriction_commutative :
  forall g : ty_ctx,
  forall v1 v2 : var,
  (g -- v1 -- v2) = (g -- v2 -- v1).
Proof. Admitted.

Theorem restriction_makes_subset :
  forall g : ty_ctx,
  forall v : var,
    VarSet.Subset (g -- v) g.
Proof. Admitted.

Theorem restriction_makes_variable_notin :
  forall g : ty_ctx,
  forall v : var,
    ~(VarSet.In v (g -- v)).
Proof. Admitted.

Theorem restr_of_notin_makes_equal :
  forall g : ty_ctx,
  forall x : var,
  forall x_gfree : ~(VarSet.In x (bound_variables g)),
    g = (g -- x).
Proof. Admitted.

Theorem disj_vars_assoc :
  forall g1 g2 g3 : ty_ctx,
  forall disj_g12 : disj_vars g1 g2,
  forall eq_g23 : g2 = g3,
    disj_vars g1 g3.
Proof. Admitted.

Theorem ctx_union_of_eql :
  forall g1 g2 g3 : ty_ctx,
  forall disj_g12 : disj_vars g1 g2,
  forall disj_g13 : disj_vars g1 g3,
  forall eq_23 : g2 = g3,
    ctx_union g1 g2 disj_g12 = ctx_union g1 g3 disj_g13.

Proof. Admitted.

Theorem disj_notin_means_disj_with_added :
  forall g1 g2 g2subv : ty_ctx,
  forall x : var,
  forall x_g1free: ~(VarSet.In x g1),
  forall disj_g12subv : disj_vars g1 g2subv,
  forall g2subv_def : g2subv = (g2 -- x),
    disj_vars g1 g2.

Proof. Admitted.

(* Set-Theory Theorems: warning a lot of admits are gonna start being applied for
   things that are obviously true.
 *)

Theorem bound_of_union_is_union_of_bound
  : forall g1 g2 : ty_ctx,
    forall disj_g12 : disj_vars g1 g2,
      bound_variables (ctx_union g1 g2 disj_g12) = VarSet.union (bound_variables g1)
                                                                (bound_variables g2)
.
Proof. Admitted.

Theorem bound_of_restr
  : forall g : ty_ctx,
    forall x : var,
      bound_variables (g -- x) = VarSet.diff (bound_variables g) (VarSet.singleton x).
Proof. Admitted.

Theorem dvars_distrib :
  forall s1 s2 s3 : ty_ctx,
  forall d1_2 : disj_vars s1 s2,
  forall d12_3 : disj_vars (bound_variables (ctxu s1 s2)) s3,
    (and (disj_vars s1 s3) (disj_vars s2 s3)).
Proof. intros. Admitted.

Theorem ctxu_sym : forall s1 s2 : ty_ctx,
    ctxu s1 s2 = ctxu s2 s1.
Proof. intros. Admitted.

Theorem ctxu_assoc : forall s1 s2 s3 : ty_ctx,
    ctxu s1 (ctxu s2 s3) = ctxu (ctxu s1 s2) s3.
Proof. intros. Admitted.

Theorem ctxu_subset :
  forall g1 g2 g2a g2b : ty_ctx,
  forall g2_decomp : g2 = ctxu g2a g2b,
  forall disj_g12 : disj_vars g1 g2,
    disj_vars g1 g2a.
Proof. intros. Admitted.

Theorem mutuallydisjoint_gets :
  forall g1 g2 g3 : ty_ctx,
  forall disj_g1_g2 : disj_vars g1 g2,
  forall disj_g1_g3 : disj_vars g1 g3,
  forall disj_g2_g2 : disj_vars g2 g3,
    disj_vars (bound_variables (ctxu g1 g2)) g3.
Proof. Admitted.

Theorem mutuallydisjoint_getsv2 :
  forall g1 g2 g3 : ty_ctx,
  forall disj_g1_g2 : disj_vars g1 g2,
  forall disj_g1_g3 : disj_vars g1 g3,
  forall disj_g2_g2 : disj_vars g2 g3,
    disj_vars g1 (bound_variables (ctxu g2 g3)).
Proof. Admitted.

Theorem in_only_one_of_disjoint :
  forall g1 g2 : ty_ctx,
  forall v : var,
  forall v_in_g2 : VarSet.In v g2,
  forall disj_g12 : disj_vars g1 g2,
    ~ (VarSet.In v g1).
Proof. Admitted.

Theorem not_in_union_means_not_in_either :
  forall g1 g2 : ty_ctx,
  forall v : var,
  forall v_notin_union : ~(VarSet.In v (VarSet.union g1 g2)),
    ~(VarSet.In v g1).
Proof. Admitted.

Theorem in_union_means_in_one :
  forall g1 g2 : ty_ctx,
  forall v : var,
  forall disj_12 : disj_vars g1 g2,
  forall v_in_union : VarSet.In v (ctx_union g1 g2 disj_12),
    (VarSet.In v g1) \/ (VarSet.In v g2).
Proof. Admitted.

Theorem ctx_union_with_restriction :
  forall g1 g2 g2subv: ty_ctx,
  forall v : var,
  forall v_notin_g1 : ~(VarSet.In v g1),
  forall g2subv_is_g2_sub_v : (g2subv = (g2 -- v)),
  forall disj_g12subv : disj_vars g1 g2subv,
  forall disj_g12 : disj_vars g1 g2,
    (ctx_union g1 g2subv disj_g12subv) = ((ctx_union g1 g2 disj_g12) -- v).
Proof. Admitted.

Theorem restriction_from_union_where_notin_one :
  forall g1 g2 : ty_ctx,
  forall v : var,
  forall v_g1free : ~(VarSet.In v g1),
  forall disj_g12 : disj_vars g1 g2,
  forall disj_g12subv : disj_vars g1 (g2 -- v),
    ((ctx_union g1 g2 disj_g12) -- v) = ctx_union g1 (g2 -- v) disj_g12subv.
Proof. Admitted.

Theorem in_restr_ifnot_same :
  forall v x : var,
  forall v_neq_x : ~(v = x),
  forall g : ty_ctx,
    VarSet.In v (g -- x) <-> VarSet.In v g.
Proof. Admitted.

Theorem var_in_singletonctx_means_equal :
  forall v x : var,
  forall t : type,
  forall v_in_singleton_of_x : VarSet.In v (judge x t),
    v = x.
Proof. Admitted.

Theorem var_in_doubletonctx_means_equal_oneof :
  forall v v1 v2 : var,
  forall t1 t2 : type,
  forall v_in_doubleton : VarSet.In v (bound_variables (ctxu (judge v1 t1) (judge v2 t2))),
    (v = v1) \/ (v = v2).
Proof. Admitted.


(************************************************************************)
(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)
(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)
(*   \VV/  **************************************************************)
(*    //   *      This file is distributed under the terms of the       *)
(*         *       GNU Lesser General Public License Version 2.1        *)
(************************************************************************)

(*i $Id: Rtrigo_alt.v 14641 2011-11-06 11:59:10Z herbelin $ i*)

Require Import Rbase.
Require Import Rfunctions.
Require Import SeqSeries.
Require Import Rtrigo_def.
Open Local Scope R_scope.

(***************************************************************)
(** Using series definitions of cos and sin                    *)
(***************************************************************)

Definition sin_term (a:R) (i:nat) : R :=
  (-1) ^ i * (a ^ (2 * i + 1) / INR (fact (2 * i + 1))).

Definition cos_term (a:R) (i:nat) : R :=
  (-1) ^ i * (a ^ (2 * i) / INR (fact (2 * i))).

Definition sin_approx (a:R) (n:nat) : R := sum_f_R0 (sin_term a) n.

Definition cos_approx (a:R) (n:nat) : R := sum_f_R0 (cos_term a) n.

(**********)
Lemma PI_4 : PI <= 4.
Proof.
  assert (H0 := PI_ineq 0).
  elim H0; clear H0; intros _ H0.
  unfold tg_alt, PI_tg in H0; simpl in H0.
  rewrite Rinv_1 in H0; rewrite Rmult_1_r in H0; unfold Rdiv in H0.
  apply Rmult_le_reg_l with (/ 4).
  apply Rinv_0_lt_compat; prove_sup0.
  rewrite <- Rinv_l_sym; [ rewrite Rmult_comm; assumption | discrR ].
Qed.

(**********)
Theorem sin_bound :
  forall (a:R) (n:nat),
    0 <= a ->
    a <= PI -> sin_approx a (2 * n + 1) <= sin a <= sin_approx a (2 * (n + 1)).
Proof.
  intros; case (Req_dec a 0); intro Hyp_a.
  rewrite Hyp_a; rewrite sin_0; split; right; unfold sin_approx in |- *;
    apply sum_eq_R0 || (symmetry  in |- *; apply sum_eq_R0);
      intros; unfold sin_term in |- *; rewrite pow_add;
        simpl in |- *; unfold Rdiv in |- *; rewrite Rmult_0_l;
          ring.
  unfold sin_approx in |- *; cut (0 < a).
  intro Hyp_a_pos.
  rewrite (decomp_sum (sin_term a) (2 * n + 1)).
  rewrite (decomp_sum (sin_term a) (2 * (n + 1))).
  replace (sin_term a 0) with a.
  cut
    (sum_f_R0 (fun i:nat => sin_term a (S i)) (pred (2 * n + 1)) <= sin a - a /\
      sin a - a <= sum_f_R0 (fun i:nat => sin_term a (S i)) (pred (2 * (n + 1))) ->
      a + sum_f_R0 (fun i:nat => sin_term a (S i)) (pred (2 * n + 1)) <= sin a /\
      sin a <= a + sum_f_R0 (fun i:nat => sin_term a (S i)) (pred (2 * (n + 1)))).
  intro; apply H1.
  set (Un := fun n:nat => a ^ (2 * S n + 1) / INR (fact (2 * S n + 1))).
  replace (pred (2 * n + 1)) with (2 * n)%nat.
  replace (pred (2 * (n + 1))) with (S (2 * n)).
  replace (sum_f_R0 (fun i:nat => sin_term a (S i)) (2 * n)) with
  (- sum_f_R0 (tg_alt Un) (2 * n)).
  replace (sum_f_R0 (fun i:nat => sin_term a (S i)) (S (2 * n))) with
  (- sum_f_R0 (tg_alt Un) (S (2 * n))).
  cut
    (sum_f_R0 (tg_alt Un) (S (2 * n)) <= a - sin a <=
      sum_f_R0 (tg_alt Un) (2 * n) ->
      - sum_f_R0 (tg_alt Un) (2 * n) <= sin a - a <=
      - sum_f_R0 (tg_alt Un) (S (2 * n))).
  intro; apply H2.
  apply alternated_series_ineq.
  unfold Un_decreasing, Un in |- *; intro;
    cut ((2 * S (S n0) + 1)%nat = S (S (2 * S n0 + 1))).
  intro; rewrite H3.
  replace (a ^ S (S (2 * S n0 + 1))) with (a ^ (2 * S n0 + 1) * (a * a)).
  unfold Rdiv in |- *; rewrite Rmult_assoc; apply Rmult_le_compat_l.
  left; apply pow_lt; assumption.
  apply Rmult_le_reg_l with (INR (fact (S (S (2 * S n0 + 1))))).
  rewrite <- H3; apply lt_INR_0; apply neq_O_lt; red in |- *; intro;
    assert (H5 := sym_eq H4); elim (fact_neq_0 _ H5).
  rewrite <- H3; rewrite (Rmult_comm (INR (fact (2 * S (S n0) + 1))));
    rewrite Rmult_assoc; rewrite <- Rinv_l_sym.
  rewrite Rmult_1_r; rewrite H3; do 2 rewrite fact_simpl; do 2 rewrite mult_INR;
    repeat rewrite Rmult_assoc; rewrite <- Rinv_r_sym.
  rewrite Rmult_1_r.
  do 2 rewrite S_INR; rewrite plus_INR; rewrite mult_INR; repeat rewrite S_INR;
    simpl in |- *;
      replace
      (((0 + 1 + 1) * (INR n0 + 1) + (0 + 1) + 1 + 1) *
        ((0 + 1 + 1) * (INR n0 + 1) + (0 + 1) + 1)) with
      (4 * INR n0 * INR n0 + 18 * INR n0 + 20); [ idtac | ring ].
  apply Rle_trans with 20.
  apply Rle_trans with 16.
  replace 16 with (Rsqr 4); [ idtac | ring_Rsqr ].
  replace (a * a) with (Rsqr a); [ idtac | reflexivity ].
  apply Rsqr_incr_1.
  apply Rle_trans with PI; [ assumption | apply PI_4 ].
  assumption.
  left; prove_sup0.
  rewrite <- (Rplus_0_r 16); replace 20 with (16 + 4);
    [ apply Rplus_le_compat_l; left; prove_sup0 | ring ].
  rewrite <- (Rplus_comm 20); pattern 20 at 1 in |- *; rewrite <- Rplus_0_r;
    apply Rplus_le_compat_l.
  apply Rplus_le_le_0_compat.
  repeat apply Rmult_le_pos.
  left; prove_sup0.
  left; prove_sup0.
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  apply Rmult_le_pos.
  left; prove_sup0.
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  apply INR_fact_neq_0.
  apply INR_fact_neq_0.
  simpl in |- *; ring.
  ring.
  assert (H3 := cv_speed_pow_fact a); unfold Un in |- *; unfold Un_cv in H3;
    unfold R_dist in H3; unfold Un_cv in |- *; unfold R_dist in |- *;
      intros; elim (H3 eps H4); intros N H5.
  exists N; intros; apply H5.
  replace (2 * S n0 + 1)%nat with (S (2 * S n0)).
  unfold ge in |- *; apply le_trans with (2 * S n0)%nat.
  apply le_trans with (2 * S N)%nat.
  apply le_trans with (2 * N)%nat.
  apply le_n_2n.
  apply (fun m n p:nat => mult_le_compat_l p n m); apply le_n_Sn.
  apply (fun m n p:nat => mult_le_compat_l p n m); apply le_n_S; assumption.
  apply le_n_Sn.
  ring.
  assert (X := exist_sin (Rsqr a)); elim X; intros.
  cut (x = sin a / a).
  intro; rewrite H3 in p; unfold sin_in in p; unfold infinite_sum in p;
    unfold R_dist in p; unfold Un_cv in |- *; unfold R_dist in |- *;
      intros.
  cut (0 < eps / Rabs a).
  intro; elim (p _ H5); intros N H6.
  exists N; intros.
  replace (sum_f_R0 (tg_alt Un) n0) with
  (a * (1 - sum_f_R0 (fun i:nat => sin_n i * Rsqr a ^ i) (S n0))).
  unfold Rminus in |- *; rewrite Rmult_plus_distr_l; rewrite Rmult_1_r;
    rewrite Ropp_plus_distr; rewrite Ropp_involutive;
      repeat rewrite Rplus_assoc; rewrite (Rplus_comm a);
        rewrite (Rplus_comm (- a)); repeat rewrite Rplus_assoc;
          rewrite Rplus_opp_l; rewrite Rplus_0_r; apply Rmult_lt_reg_l with (/ Rabs a).
  apply Rinv_0_lt_compat; apply Rabs_pos_lt; assumption.
  pattern (/ Rabs a) at 1 in |- *; rewrite <- (Rabs_Rinv a Hyp_a).
  rewrite <- Rabs_mult; rewrite Rmult_plus_distr_l; rewrite <- Rmult_assoc;
    rewrite <- Rinv_l_sym; [ rewrite Rmult_1_l | assumption ];
      rewrite (Rmult_comm (/ a)); rewrite (Rmult_comm (/ Rabs a));
        rewrite <- Rabs_Ropp; rewrite Ropp_plus_distr; rewrite Ropp_involutive;
          unfold Rminus, Rdiv in H6; apply H6; unfold ge in |- *;
            apply le_trans with n0; [ exact H7 | apply le_n_Sn ].
  rewrite (decomp_sum (fun i:nat => sin_n i * Rsqr a ^ i) (S n0)).
  replace (sin_n 0) with 1.
  simpl in |- *; rewrite Rmult_1_r; unfold Rminus in |- *;
    rewrite Ropp_plus_distr; rewrite <- Rplus_assoc; rewrite Rplus_opp_r;
      rewrite Rplus_0_l; rewrite Ropp_mult_distr_r_reverse;
        rewrite <- Ropp_mult_distr_l_reverse; rewrite scal_sum;
          apply sum_eq.
  intros; unfold sin_n, Un, tg_alt in |- *;
    replace ((-1) ^ S i) with (- (-1) ^ i).
  replace (a ^ (2 * S i + 1)) with (Rsqr a * Rsqr a ^ i * a).
  unfold Rdiv in |- *; ring.
  rewrite pow_add; rewrite pow_Rsqr; simpl in |- *; ring.
  simpl in |- *; ring.
  unfold sin_n in |- *; unfold Rdiv in |- *; simpl in |- *; rewrite Rinv_1;
    rewrite Rmult_1_r; reflexivity.
  apply lt_O_Sn.
  unfold Rdiv in |- *; apply Rmult_lt_0_compat.
  assumption.
  apply Rinv_0_lt_compat; apply Rabs_pos_lt; assumption.
  unfold sin in |- *; case (exist_sin (Rsqr a)).
  intros; cut (x = x0).
  intro; rewrite H3; unfold Rdiv in |- *.
  symmetry  in |- *; apply Rinv_r_simpl_m; assumption.
  unfold sin_in in p; unfold sin_in in s; eapply uniqueness_sum.
  apply p.
  apply s.
  intros; elim H2; intros.
  replace (sin a - a) with (- (a - sin a)); [ idtac | ring ].
  split; apply Ropp_le_contravar; assumption.
  replace (- sum_f_R0 (tg_alt Un) (S (2 * n))) with
  (-1 * sum_f_R0 (tg_alt Un) (S (2 * n))); [ rewrite scal_sum | ring ].
  apply sum_eq; intros; unfold sin_term, Un, tg_alt in |- *;
    replace ((-1) ^ S i) with (-1 * (-1) ^ i).
  unfold Rdiv in |- *; ring.
  reflexivity.
  replace (- sum_f_R0 (tg_alt Un) (2 * n)) with
  (-1 * sum_f_R0 (tg_alt Un) (2 * n)); [ rewrite scal_sum | ring ].
  apply sum_eq; intros.
  unfold sin_term, Un, tg_alt in |- *;
    replace ((-1) ^ S i) with (-1 * (-1) ^ i).
  unfold Rdiv in |- *; ring.
  reflexivity.
  replace (2 * (n + 1))%nat with (S (S (2 * n))).
  reflexivity.
  ring.
  replace (2 * n + 1)%nat with (S (2 * n)).
  reflexivity.
  ring.
  intro; elim H1; intros.
  split.
  apply Rplus_le_reg_l with (- a).
  rewrite <- Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_l;
    rewrite (Rplus_comm (- a)); apply H2.
  apply Rplus_le_reg_l with (- a).
  rewrite <- Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_l;
    rewrite (Rplus_comm (- a)); apply H3.
  unfold sin_term in |- *; simpl in |- *; unfold Rdiv in |- *; rewrite Rinv_1;
    ring.
  replace (2 * (n + 1))%nat with (S (S (2 * n))).
  apply lt_O_Sn.
  ring.
  replace (2 * n + 1)%nat with (S (2 * n)).
  apply lt_O_Sn.
  ring.
  inversion H; [ assumption | elim Hyp_a; symmetry  in |- *; assumption ].
Qed.

(**********)
Lemma cos_bound :
  forall (a:R) (n:nat),
    - PI / 2 <= a ->
    a <= PI / 2 ->
    cos_approx a (2 * n + 1) <= cos a <= cos_approx a (2 * (n + 1)).
Proof.
  cut
    ((forall (a:R) (n:nat),
      0 <= a ->
      a <= PI / 2 ->
      cos_approx a (2 * n + 1) <= cos a <= cos_approx a (2 * (n + 1))) ->
    forall (a:R) (n:nat),
      - PI / 2 <= a ->
      a <= PI / 2 ->
      cos_approx a (2 * n + 1) <= cos a <= cos_approx a (2 * (n + 1))).
  intros H a n; apply H.
  intros; unfold cos_approx in |- *.
  rewrite (decomp_sum (cos_term a0) (2 * n0 + 1)).
  rewrite (decomp_sum (cos_term a0) (2 * (n0 + 1))).
  replace (cos_term a0 0) with 1.
  cut
    (sum_f_R0 (fun i:nat => cos_term a0 (S i)) (pred (2 * n0 + 1)) <= cos a0 - 1 /\
      cos a0 - 1 <=
      sum_f_R0 (fun i:nat => cos_term a0 (S i)) (pred (2 * (n0 + 1))) ->
      1 + sum_f_R0 (fun i:nat => cos_term a0 (S i)) (pred (2 * n0 + 1)) <= cos a0 /\
      cos a0 <=
      1 + sum_f_R0 (fun i:nat => cos_term a0 (S i)) (pred (2 * (n0 + 1)))).
  intro; apply H2.
  set (Un := fun n:nat => a0 ^ (2 * S n) / INR (fact (2 * S n))).
  replace (pred (2 * n0 + 1)) with (2 * n0)%nat.
  replace (pred (2 * (n0 + 1))) with (S (2 * n0)).
  replace (sum_f_R0 (fun i:nat => cos_term a0 (S i)) (2 * n0)) with
  (- sum_f_R0 (tg_alt Un) (2 * n0)).
  replace (sum_f_R0 (fun i:nat => cos_term a0 (S i)) (S (2 * n0))) with
  (- sum_f_R0 (tg_alt Un) (S (2 * n0))).
  cut
    (sum_f_R0 (tg_alt Un) (S (2 * n0)) <= 1 - cos a0 <=
      sum_f_R0 (tg_alt Un) (2 * n0) ->
      - sum_f_R0 (tg_alt Un) (2 * n0) <= cos a0 - 1 <=
      - sum_f_R0 (tg_alt Un) (S (2 * n0))).
  intro; apply H3.
  apply alternated_series_ineq.
  unfold Un_decreasing in |- *; intro; unfold Un in |- *.
  cut ((2 * S (S n1))%nat = S (S (2 * S n1))).
  intro; rewrite H4;
    replace (a0 ^ S (S (2 * S n1))) with (a0 ^ (2 * S n1) * (a0 * a0)).
  unfold Rdiv in |- *; rewrite Rmult_assoc; apply Rmult_le_compat_l.
  apply pow_le; assumption.
  apply Rmult_le_reg_l with (INR (fact (S (S (2 * S n1))))).
  rewrite <- H4; apply lt_INR_0; apply neq_O_lt; red in |- *; intro;
    assert (H6 := sym_eq H5); elim (fact_neq_0 _ H6).
  rewrite <- H4; rewrite (Rmult_comm (INR (fact (2 * S (S n1)))));
    rewrite Rmult_assoc; rewrite <- Rinv_l_sym.
  rewrite Rmult_1_r; rewrite H4; do 2 rewrite fact_simpl; do 2 rewrite mult_INR;
    repeat rewrite Rmult_assoc; rewrite <- Rinv_r_sym.
  rewrite Rmult_1_r; do 2 rewrite S_INR; rewrite mult_INR; repeat rewrite S_INR;
    simpl in |- *;
      replace
      (((0 + 1 + 1) * (INR n1 + 1) + 1 + 1) * ((0 + 1 + 1) * (INR n1 + 1) + 1))
    with (4 * INR n1 * INR n1 + 14 * INR n1 + 12); [ idtac | ring ].
  apply Rle_trans with 12.
  apply Rle_trans with 4.
  replace 4 with (Rsqr 2); [ idtac | ring_Rsqr ].
  replace (a0 * a0) with (Rsqr a0); [ idtac | reflexivity ].
  apply Rsqr_incr_1.
  apply Rle_trans with (PI / 2).
  assumption.
  unfold Rdiv in |- *; apply Rmult_le_reg_l with 2.
  prove_sup0.
  rewrite <- Rmult_assoc; rewrite Rinv_r_simpl_m.
  replace 4 with 4; [ apply PI_4 | ring ].
  discrR.
  assumption.
  left; prove_sup0.
  pattern 4 at 1 in |- *; rewrite <- Rplus_0_r; replace 12 with (4 + 8);
    [ apply Rplus_le_compat_l; left; prove_sup0 | ring ].
  rewrite <- (Rplus_comm 12); pattern 12 at 1 in |- *; rewrite <- Rplus_0_r;
    apply Rplus_le_compat_l.
  apply Rplus_le_le_0_compat.
  repeat apply Rmult_le_pos.
  left; prove_sup0.
  left; prove_sup0.
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  apply Rmult_le_pos.
  left; prove_sup0.
  replace 0 with (INR 0); [ apply le_INR; apply le_O_n | reflexivity ].
  apply INR_fact_neq_0.
  apply INR_fact_neq_0.
  simpl in |- *; ring.
  ring.
  assert (H4 := cv_speed_pow_fact a0); unfold Un in |- *; unfold Un_cv in H4;
    unfold R_dist in H4; unfold Un_cv in |- *; unfold R_dist in |- *;
      intros; elim (H4 eps H5); intros N H6; exists N; intros.
  apply H6; unfold ge in |- *; apply le_trans with (2 * S N)%nat.
  apply le_trans with (2 * N)%nat.
  apply le_n_2n.
  apply (fun m n p:nat => mult_le_compat_l p n m); apply le_n_Sn.
  apply (fun m n p:nat => mult_le_compat_l p n m); apply le_n_S; assumption.
  assert (X := exist_cos (Rsqr a0)); elim X; intros.
  cut (x = cos a0).
  intro; rewrite H4 in p; unfold cos_in in p; unfold infinite_sum in p;
    unfold R_dist in p; unfold Un_cv in |- *; unfold R_dist in |- *;
      intros.
  elim (p _ H5); intros N H6.
  exists N; intros.
  replace (sum_f_R0 (tg_alt Un) n1) with
  (1 - sum_f_R0 (fun i:nat => cos_n i * Rsqr a0 ^ i) (S n1)).
  unfold Rminus in |- *; rewrite Ropp_plus_distr; rewrite Ropp_involutive;
    repeat rewrite Rplus_assoc; rewrite (Rplus_comm 1);
      rewrite (Rplus_comm (-1)); repeat rewrite Rplus_assoc;
        rewrite Rplus_opp_l; rewrite Rplus_0_r; rewrite <- Rabs_Ropp;
          rewrite Ropp_plus_distr; rewrite Ropp_involutive;
            unfold Rminus in H6; apply H6.
  unfold ge in |- *; apply le_trans with n1.
  exact H7.
  apply le_n_Sn.
  rewrite (decomp_sum (fun i:nat => cos_n i * Rsqr a0 ^ i) (S n1)).
  replace (cos_n 0) with 1.
  simpl in |- *; rewrite Rmult_1_r; unfold Rminus in |- *;
    rewrite Ropp_plus_distr; rewrite <- Rplus_assoc; rewrite Rplus_opp_r;
      rewrite Rplus_0_l;
        replace (- sum_f_R0 (fun i:nat => cos_n (S i) * (Rsqr a0 * Rsqr a0 ^ i)) n1)
    with
      (-1 * sum_f_R0 (fun i:nat => cos_n (S i) * (Rsqr a0 * Rsqr a0 ^ i)) n1);
      [ idtac | ring ]; rewrite scal_sum; apply sum_eq;
        intros; unfold cos_n, Un, tg_alt in |- *.
  replace ((-1) ^ S i) with (- (-1) ^ i).
  replace (a0 ^ (2 * S i)) with (Rsqr a0 * Rsqr a0 ^ i).
  unfold Rdiv in |- *; ring.
  rewrite pow_Rsqr; reflexivity.
  simpl in |- *; ring.
  unfold cos_n in |- *; unfold Rdiv in |- *; simpl in |- *; rewrite Rinv_1;
    rewrite Rmult_1_r; reflexivity.
  apply lt_O_Sn.
  unfold cos in |- *; case (exist_cos (Rsqr a0)); intros; unfold cos_in in p;
    unfold cos_in in c; eapply uniqueness_sum.
  apply p.
  apply c.
  intros; elim H3; intros; replace (cos a0 - 1) with (- (1 - cos a0));
    [ idtac | ring ].
  split; apply Ropp_le_contravar; assumption.
  replace (- sum_f_R0 (tg_alt Un) (S (2 * n0))) with
  (-1 * sum_f_R0 (tg_alt Un) (S (2 * n0))); [ rewrite scal_sum | ring ].
  apply sum_eq; intros; unfold cos_term, Un, tg_alt in |- *;
    replace ((-1) ^ S i) with (-1 * (-1) ^ i).
  unfold Rdiv in |- *; ring.
  reflexivity.
  replace (- sum_f_R0 (tg_alt Un) (2 * n0)) with
  (-1 * sum_f_R0 (tg_alt Un) (2 * n0)); [ rewrite scal_sum | ring ];
  apply sum_eq; intros; unfold cos_term, Un, tg_alt in |- *;
    replace ((-1) ^ S i) with (-1 * (-1) ^ i).
  unfold Rdiv in |- *; ring.
  reflexivity.
  replace (2 * (n0 + 1))%nat with (S (S (2 * n0))).
  reflexivity.
  ring.
  replace (2 * n0 + 1)%nat with (S (2 * n0)).
  reflexivity.
  ring.
  intro; elim H2; intros; split.
  apply Rplus_le_reg_l with (-1).
  rewrite <- Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_l;
    rewrite (Rplus_comm (-1)); apply H3.
  apply Rplus_le_reg_l with (-1).
  rewrite <- Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_l;
    rewrite (Rplus_comm (-1)); apply H4.
  unfold cos_term in |- *; simpl in |- *; unfold Rdiv in |- *; rewrite Rinv_1;
    ring.
  replace (2 * (n0 + 1))%nat with (S (S (2 * n0))).
  apply lt_O_Sn.
  ring.
  replace (2 * n0 + 1)%nat with (S (2 * n0)).
  apply lt_O_Sn.
  ring.
  intros; case (total_order_T 0 a); intro.
  elim s; intro.
  apply H; [ left; assumption | assumption ].
  apply H; [ right; assumption | assumption ].
  cut (0 < - a).
  intro; cut (forall (x:R) (n:nat), cos_approx x n = cos_approx (- x) n).
  intro; rewrite H3; rewrite (H3 a (2 * (n + 1))%nat); rewrite cos_sym; apply H.
  left; assumption.
  rewrite <- (Ropp_involutive (PI / 2)); apply Ropp_le_contravar;
    unfold Rdiv in |- *; unfold Rdiv in H0; rewrite <- Ropp_mult_distr_l_reverse;
      exact H0.
  intros; unfold cos_approx in |- *; apply sum_eq; intros;
    unfold cos_term in |- *; do 2 rewrite pow_Rsqr; rewrite Rsqr_neg;
      unfold Rdiv in |- *; reflexivity.
  apply Ropp_0_gt_lt_contravar; assumption.
Qed.


Set Warnings "-notation-overridden,-parsing".
Require Import Program.Basics.
Require Import FunctionalExtensionality.
Require Import Strings.String.
Require Import Sect2.

(********************************)
(* Towards More Abstract Lenses *)
(********************************)

(* Isomorphism between `MonadState A (state S)` and `lens S A` *)

Definition ms_2_lens {S A} (ms : MonadState A (state S)) : lens S A :=
{| view s     := evalState get s
;  update s a := execState (put a) s
|}.

Instance lens_2_ms {S A} (ln : lens S A) : MonadState A (state S) :=
{ get   := mkState (fun s => (view ln s, s))
; put a := mkState (fun s => (tt, update ln s a))
}.

Lemma MonadState_state_s_induces_lens :
  forall {S A : Type} (ms : MonadState A (state S)),
    @MonadStateLaws A (state S) _ _ ms -> lensLaws (ms_2_lens ms).
Proof.
  intros.
  unfold ms_2_lens.
  assert (F : forall s, put (evalState get s) = get >> put (evalState get s)).
  { intros.
    rewrite <- (non_eff_get (put (evalState get s))).
    now rewrite (general_getget (fun _ => put (evalState get s))). }
  destruct H.
  constructor; intros; simpl.

  - (* view_update *)
    rewrite F.
    rewrite <- execexec_is_execgtgt.
    rewrite execevalexec_is_execbind.
    now rewrite get_put.

  - (* update_view *)
    rewrite execeval_is_evalgtgt.
    rewrite put_get.
    now rewrite eval_ma_gtgt_retx_is_x.

  - (* updte_update *)
    rewrite execexec_is_execgtgt.
    now rewrite put_put.
Qed.

Lemma lens_induces_MonadState_state_s :
  forall {S A : Type} (ln : lens S A),
    lensLaws ln -> @MonadStateLaws A (state S) _ _ (lens_2_ms ln).
Proof.
  intros.
  destruct H.
  split;
    simpl;
    intros;
    repeat state_reason;
    [rewrite view_update | rewrite update_view | rewrite update_update];
    auto.
Qed.

Proposition ms_iso_lens :
  forall {S A} (ln : lens S A) (ms : MonadState A (state S)),
    lensLaws ln ->
    @MonadStateLaws _ _ _ _ ms ->
    ((ms_2_lens ∘ lens_2_ms) ln = ln) /\
    ((lens_2_ms ∘ ms_2_lens) ms = ms).
Proof.
  unfold ms_2_lens. unfold lens_2_ms.
  unfold compose.
  intros.
  split; simpl.

  - (* ms_2_lens ∘ lens_2_ms *)
    destruct ln.
    auto.

  - (* lens_2_ms ∘ ms_2_lens *)
    assert (G0 : (fun s : S => (evalState get s, s)) =
                 (fun s : S => (evalState get s, execState get s))).
    { functional_extensionality_i.
      apply f_equal.
      now rewrite get_leaves_s_as_is. }
    rewrite G0.
    destruct ms.
    simpl.
    assert (G1 :
      {| runState := fun s : S => (evalState get s, execState get s) |} = get).
    { destruct get.
      unfold evalState. unfold execState.
      unwrap_layer.
      simpl.
      now destruct (runState x). }
    rewrite G1.
    assert (G2 :
      (fun a : A => {| runState := fun s : S => (tt, execState (put a) s) |}) = put).
    { functional_extensionality_i.
      destruct (put x).
      unwrap_layer.
      unfold execState.
      simpl.
      destruct (runState x0).
      now destruct u. }
    now rewrite G2.
Qed.

(* Lens Algebra definition, just a record *)

Record lensAlg (p : Type -> Type) (A : Type) `{M : Monad p} : Type :=
{ view : p A
; update : A -> p unit
; modify (f : A -> A) : p unit := view >>= (update ∘ f)
}.
Arguments view [p A _ _].
Arguments update [p A _ _].
Arguments modify [p A _ _].
Notation "ln %~ f" := (modify ln f) (at level 40, no associativity).

Record lensAlgLaws {p A} `{Monad p} (ln : lensAlg p A) : Type :=
{ view_view : view ln >>= (fun s1 => view ln >>= (fun s2 => ret (s1, s2))) =
              view ln >>= (fun s => ret (s, s))
; view_update : view ln >>= update ln = ret tt
; update_view : forall s, update ln s >> view ln = update ln s >> ret s
; update_update : forall s1 s2, update ln s1 >> update ln s2 = update ln s2
}.

Lemma general_viewview :
  forall {p : Type -> Type} {A X : Type}
        `{ml : MonadLaws p}
         (ln : lensAlg p A)
         (lnl : lensAlgLaws ln)
         (k : A * A -> p X),
    view ln >>= (fun x1 => view ln >>= (fun x2 => k (x1, x2))) =
    view ln >>= (fun x1 => k (x1, x1)).
Proof.
  intros.
  destruct ml.
  destruct lnl.
  assert (G : view ln >>= (fun x1 : A => k (x1, x1)) =
              view ln >>= (fun x1 : A => ret (x1, x1) >>= k)).
  { unwrap_layer. now rewrite left_id. }
  rewrite G.
  rewrite <- assoc.
  rewrite <- view_view0.
  rewrite -> assoc.
  unwrap_layer.
  rewrite -> assoc.
  unwrap_layer.
  now rewrite left_id.
Qed.

Lemma non_eff_view :
  forall  {p : Type -> Type} {A}
         `{ml : MonadLaws p}
          (ln : lensAlg p A)
          (lnl : lensAlgLaws ln)
          {X}
          (k : p X),
  view ln >> k = k.
Proof.
  intros.
  pose proof (@general_viewview p A X H _ ml ln lnl) as J.
  destruct ml.
  destruct lnl.
  rewrite <- (left_id unit _ tt (fun _ => k)).
  rewrite <- view_update0.
  repeat rewrite assoc.
  now rewrite (J (fun pair => update ln (snd pair) >> k)).
Qed.

(* `MonadState_state` is isomorphic to `identityLn` *)

(* We only show one way, since the full isomorphism follows from the previous
   proposition for the general case. *)
Corollary MonadState_state_is_identity_lens :
  forall A, ms_2_lens MonadState_state = identityLn A.
Proof. auto. Qed.

(*************************)
(* University Data Layer *)
(*************************)

Record DepartmentAlg p Dep `{id : MonadState Dep p} :=
{ budgetLn : lensAlg p nat }.
Arguments budgetLn [p Dep _ _ id].

Record UniversityAlg p Univ `{id : MonadState Univ p} :=
{ nameLn : lensAlg p string
; q : Type -> Type
; Dep : Type
; fq : Functor q
; mq : Monad q
; msq : MonadState Dep q
; ev : DepartmentAlg q Dep
; mathDepLn : lensAlg p Dep
}.

Definition doubleDepBudget p Dep
   `{MonadState Dep p}
    (data : DepartmentAlg p Dep) : p unit :=
  budgetLn data %~ (fun b => b * 2).

(* However, we can't implement an analogous for `duplicateUnivBudget`!!! *)