Require Export Base.
Require Export MarkedGraph.

Require Import Monad.
Import MonadNotations.
Open Scope monad_scope.

Require Import List.
Import ListNotations.
Open Scope list_scope.

Require Import Coq.Logic.FunctionalExtensionality.
Require Import Omega.

Require Import Lia (* Linear integer arithmetic tactics *).

Section Circuit.

(** Latches are either even or odd *)
Variable even odd : Set.

(** Equality over latches is decidable *)
Context `{Heven : eq_dec even} `{Hodd : eq_dec odd}.

(** * Latches, events, and traces *)
Section LatchSequence.

  (** Latches are either even or odd *)
  Inductive latch : Set :=
  | Odd : odd -> latch
  | Even : even -> latch
  .

  (** An event is a pair of a key and a value. *)
  Inductive event key val :=
  | Event : key -> val -> event key val.

  (* OLD DEFINITION:
   (** Events are either the rise or fall of a latch's clock *)
   Inductive event : Set :=
  | Rise : latch -> event
  | Fall : latch -> event
  . *)
  Arguments Event {key val}.

  (** A trace is a list of events *)
  Definition trace latch val := tail_list (event latch val).

  (** Latches need not hold single bits; they can also hold numeric values, the
  symbolic value X (don't care), and the symbolic value Z (floating). *)
  Inductive value :=
  | Num : nat -> value
(*
  | Bit0 : value
  | Bit1 : value
*)
  | X  : value.
  Definition Bit0 := Num 0.
  Definition Bit1 := Num 1.

  Definition Rise l : event latch bool := Event l true.
  Definition Fall l : event latch bool := Event l false.
  Definition val_to_nat (v : value) : nat :=
  match v with
  | Num n => n
  | X     => 0
  end.

  Definition neg_value (v : value) : value :=
    match v with
    | Num 0 => Num 1
    | Num 1 => Num 0
    | _     => v
    end.
  Definition inc_value (v : value) : value :=
    match v with
    | Num n => Num (n+1)
    | _     => v
    end.
  Definition dec_value (v : value) : value :=
    match v with
    | Num n => Num (n-1)
    | _     => v
    end.

  Inductive val_is_bit : value -> Prop :=
  | val_bit0 : val_is_bit Bit0
  | val_bit1 : val_is_bit Bit1.
  Hint Constructors val_is_bit : circuit.

  Lemma val_is_bit_neg_neg : forall v, val_is_bit v -> neg_value (neg_value v) = v.
  Proof.
    intros v Hv; inversion Hv; subst; auto.
  Qed.
  Lemma val_is_bit_neq : forall v1 v2, val_is_bit v1 -> val_is_bit v2 -> v1 <> v2 -> neg_value v1 = v2.
  Proof.
    intros v1 v2 Hv1 Hv2 Hneq;
      inversion Hv1; inversion Hv2; subst; auto;
        find_contradiction.
  Qed.
  Lemma val_is_bit_neg_inversion : forall v1 v2, val_is_bit v2 ->
                                                 v1 = neg_value v2 ->
                                                 neg_value v1 = v2.
  Proof.
    intros v1 v2 Hv2 Heq; subst. rewrite val_is_bit_neg_neg; auto.
  Qed.

  Lemma val_to_nat_dec : forall v, val_to_nat (dec_value v) = val_to_nat v - 1.
  Proof. intros v; destruct v; auto. Qed.
  Lemma val_to_nat_inc : forall v, v <> X -> val_to_nat (inc_value v) = val_to_nat v + 1.
  Proof. intros v Hv; destruct v; auto. find_contradiction. Qed.

  Lemma val_is_bit_neq_neg : forall v1 v2,
    val_is_bit v1 \/ val_is_bit v2 ->
    neg_value v1 = v2 ->
    v1 <> v2.
  Proof.
    intros v1 v2 [H | H] Heq; inversion H; subst; try (inversion 1; fail);
      destruct v1 as [[|[|n]]|]; try find_contradiction.
  Qed.

  (** A transparency state records whether latches are currently transparent or opaque. *)
  Inductive transparency := Transparent | Opaque.
  Definition tstate := latch -> transparency.

  (** ** Decidability of values, latches, and events *)

  Instance value_eq_dec : eq_dec value.
  Proof.
    constructor. intros [x | ] [y | ];
    try (left; reflexivity);
    try (right; discriminate).
    compare x y; auto.
    right. congruence.
  Defined.
  Instance latch_eq_dec : eq_dec latch.
  Proof.
    split.
    intros [o1 | e1] [o2 | e2];
    try (right; inversion 1; fail).
    * destruct Hodd as [H].
      destruct (H o1 o2);
        [subst; left; reflexivity | right; inversion 1; contradiction].
    * destruct Heven as [H].
      destruct (H e1 e2);
        [subst; left; reflexivity | right; inversion 1; contradiction].
  Defined.
  Instance event_eq_dec {key val} `{eq_dec key} `{eq_dec val} : eq_dec (event key val).
  Proof.
    constructor.
    intros [l1 v1] [l2 v2];
      try (left; reflexivity);
      try (right; inversion 1; fail).
    destruct (Dec l1 l2); destruct (Dec v1 v2); subst;
      try (left; reflexivity);
    try (right; inversion 1; contradiction).
(*. OLD PROOF:
    intros [l1 | l1] [l2 | l2].
    * destruct (Dec l1 l2); [ subst; auto | ].
      right. inversion 1. contradiction.
    * right. inversion 1.
    * right. inversion 1.
    * destruct (Dec l1 l2); [ subst; auto | ].
      right. inversion 1. contradiction.
*)
  Defined.

  (** Calculate the number of occurrences of an event in a trace *)
  Fixpoint num_events {A} `{eq_dec A} (e : event latch A) (t : trace latch A) : nat :=
    match t with
    | t_empty => 0
    | t' ▶ e' => if e =? e'
                 then 1 + num_events e t'
                 else num_events e t'
    end.

  (** Calculate the set of transparent latches after executing the trace t *)
  Fixpoint transparent (t : trace latch bool) : tstate :=
    match t with
    | t_empty => fun l => match l with
                          | Even _ => Opaque
                          | Odd _ => Transparent
                          end
    | t' ▶ e => fun l => if Rise l =? e then Transparent
                              else if Fall l =? e then Opaque
                              else transparent t' l
    end.

End LatchSequence.

Existing Instance latch_eq_dec.
Existing Instance value_eq_dec.
Existing Instance event_eq_dec.

(** * Circuits *)
Section Circuits.

  (** A state (e.g. of a set of latches) maps each of those latches to values *)
  Definition state (tp : Set) := tp -> value.

  Definition update {X : Set} `{eq_dec X} (σ : state X) (x : X) (v : value) : state X :=
    fun y => if x =? y then v
             else σ y.
  Definition update_event {X : Set} `{eq_dec X} (σ : state X) (e : event X value) : state X :=
    match e with
    | Event _ _ i v => update σ i v
    end.

  (** Restrict a state to only its even or odd members. *)
  Definition odd_state {P : odd -> Prop}
                       (s : state latch) : state {o : odd & P o} :=
    fun o => s (Odd (projT1 o)).
  Definition even_state {P : even -> Prop}
                        (s : state latch) : state {e : even & P e} :=
    fun o => s (Even (projT1 o)).

  (** A circuit consists of (1) lists of its even-odd and odd-even neighbors;
  and (2) for each latch, a next_state function. *)
  Record circuit : Set :=
  { even_odd_neighbors : list (even * odd)
  ; odd_even_neighbors : list (odd * even)
  ; next_state_e (e : even) : state {o : odd  & In (o,e) odd_even_neighbors} -> value
  ; next_state_o  (o : odd)  : state {e : even & In (e,o) even_odd_neighbors} -> value
  }.

  (** A generalization of even-odd and odd-even neighbors *)
  Inductive neighbor c : latch -> latch  -> Prop :=
  | EO_neighbor E O : In (E,O) (even_odd_neighbors c) -> neighbor c (Even E) (Odd O)
  | OE_neighbor O E : In (O,E) (odd_even_neighbors c) -> neighbor c (Odd O) (Even E).

  (** The next-state function *)
  Definition next_state (c : circuit) (st : state latch) (l : latch) : value :=
    match l with
    | Even e => next_state_e c e (odd_state st)
    | Odd o  => next_state_o c o (even_state st)
    end.

  (** * Asynchronous execution *)

  Reserved Notation "⟨ c , st ⟩⊢ t ↓ l ↦{ O } v" (no associativity, at level 90).
  Inductive async (c : circuit) (st0 : state latch)
                    : trace latch bool -> latch -> transparency -> value -> Prop :=
  | async_nil : forall E,
    ⟨c,st0⟩⊢ t_empty ↓ Even E ↦{Opaque} st0 (Even E)

  | async_transparent : forall l t st v,
    transparent t l = Transparent ->
    (forall l', neighbor c l' l -> ⟨c,st0⟩⊢ t ↓ l' ↦{transparent t l'} st l') ->
    v = next_state c st l ->
    ⟨c,st0⟩⊢ t ↓ l ↦{Transparent} v

  | async_opaque : forall l e t' v,
    e <> Fall l ->
    transparent (t' ▶ e) l = Opaque ->
    ⟨c,st0⟩⊢ t' ↓ l ↦{Opaque} v ->
    ⟨c,st0⟩⊢ t' ▶ e ↓ l ↦{Opaque} v

  | async_opaque_fall : forall l e t' v st,
    e = Fall l ->
    (forall l', neighbor c l' l -> ⟨c,st0⟩⊢ t' ↓ l' ↦{transparent t' l'} st l') ->
    v = next_state c st l ->
    ⟨c,st0⟩⊢ t' ▶ e ↓ l ↦{Opaque} v

  where "⟨ c , st ⟩⊢ t ↓ l ↦{ O } v" := (async c st t l O v).

  (** ** Helper lemmas *)
Lemma async_b : forall c st0 l O t v,
    ⟨c,st0⟩⊢ t ↓ l ↦{O} v ->
    transparent t l = O.
Proof.
  intros c st0 l O t v H.
  induction H; auto. simpl.
  subst. simpl.
  compare_next; auto.
Qed.

Lemma next_state_eq : forall c st1 st2 l,
  (forall l', neighbor c l' l -> st1 l' = st2 l') ->
  next_state c st1 l = next_state c st2 l.
Proof.
  intros c st1 st2 l H.
  destruct l as [O | E]; simpl; apply f_equal; unfold even_state, odd_state;
    apply functional_extensionality; intros [l' Hl']; simpl;
    apply H; constructor; auto.
Qed.

Lemma async_injective : forall c st0 l b1 t v1,
    ⟨c,st0⟩⊢ t ↓ l ↦{b1} v1 ->
    forall b2 v2, ⟨c,st0⟩⊢ t ↓ l ↦{b2} v2 ->
    v1 = v2.
Proof.
  intros c st0 l b1 t v1 H1.
  induction H1; intros b2 v2 H2';
    inversion H2'; subst; simpl in *; find_contradiction; auto.

  * apply next_state_eq.
    intros l' Hl'.
    eapply H1; eauto.
  * compare_next.
  * compare (Rise l) e.
    eapply IHasync; eauto.
  * compare_next.
  * apply next_state_eq.
    intros l' Hl'.
    eapply H1; eauto.
Qed.

  (** * Synchronous execution *)

  (** Single unit of update for odd/even latches *)

  Definition sync_update_odd (c : circuit) (st : state latch) : state latch :=
    fun l =>
    match l with
    | Odd o => next_state_o c o (even_state st)
    | Even e => st (Even e)
    end.

  Definition sync_update_even (c : circuit) (st : state latch) : state latch :=
    fun l =>
    match l with
    | Odd o => st (Odd o)
    | Even e => next_state_e c e (odd_state st)
    end.

  (** Main definition of synchronous execution *)

  Fixpoint sync_eval (c : circuit) (st : state latch) (n : nat) : state latch :=
    match n with
    | 0 => st
    | S n' => sync_update_even c (sync_update_odd c (sync_eval c st n'))
    end.

  (** ** Helper lemmas *)
  Lemma sync_eval_odd_0 : forall c st E,
        sync_eval c st 0 (Even E) = st (Even E).
  Proof.
    intros. reflexivity.
  Qed.

  Lemma sync_eval_even : forall (c : circuit) (st : state latch) n E,
        sync_eval c st (S n) (Even E) = next_state_e c E (odd_state (sync_eval c st (S n))).
  Proof. auto. Qed.
  Lemma sync_eval_odd : forall c st n O,
        sync_eval c st (S n) (Odd O) = next_state_o c O (even_state (sync_eval c st n)).
  Proof. auto. Qed.

  Lemma sync_eval_S : forall c init_st n l st,
    (forall l', neighbor c l' l ->
                 st l' = match l with
                        | Even _ => sync_eval c init_st (S n) l'
                        | Odd _  => sync_eval c init_st n l'
                        end) ->
    sync_eval c init_st (S n) l = next_state c st l.
  Proof.
    intros c init_st n [O | E] st Hst; subst.
      + simpl. apply f_equal. apply functional_extensionality. intros [E HE]. simpl.
        unfold even_state. simpl. rewrite Hst; auto. constructor; auto.
      + simpl. apply f_equal. apply functional_extensionality. intros [O HO]. simpl.
        unfold odd_state. simpl. rewrite Hst; auto. constructor; auto.
  Qed.

  Lemma sync_eval_gt : forall c init_st n l st,
    0 < n ->
    (forall l', neighbor c l' l ->
                 st l' = match l with
                        | Even _ => sync_eval c init_st n l'
                        | Odd _  => sync_eval c init_st (n-1) l'
                        end) ->
    sync_eval c init_st n l = next_state c st l.
  Proof.
    intros.
    destruct n; [find_contradiction | ].
    replace (S n - 1) with n in * by omega.
    apply sync_eval_S; auto.
  Qed.

End Circuits.

Notation "⟨ c , st  ⟩⊢ t ↓ l ↦{ O } v" := (async c st t l O v) (no associativity, at level 90).

(** * Flow equivalence

A marked graph [M] is *flow equivalent* to a circuit [c] at state [st0] if, for all traces [t] accepted by the marked graph [M]: if [l] maps to [v] in the state obtained by asynchronously executing [t] in the circuit [c] from the state [st0], then [v] is the ith *synchronous* value latched by [l], where [i] is the number of occurrences of [Fall l] in [t].

*)

Section FlowEquivalence.

  Definition flow_equivalence (M : marked_graph (event latch bool))
                              (c : circuit)
                              (st0 : state latch) :=
    forall l t v,
      (exists m, [M]⊢ t ↓ m) ->
      ⟨c,st0⟩⊢ t ↓ l ↦{Opaque} v ->
       v = sync_eval c st0 (num_events (Fall l) t) l.

End FlowEquivalence.

End Circuit.

(* begin hide *)
Arguments flow_equivalence {even odd Heven Hodd} M.

Arguments Odd {even odd}.
Arguments Even {even odd}.
Arguments transparent {even odd Heven Hodd}.

Arguments neighbor {even odd}.

Arguments Event {key val}.
Arguments Rise {even odd}.
Arguments Fall {even odd}.
Arguments num_events {even odd Heven Hodd A Adec} : rename.

Arguments odd_even_neighbors {even odd}.
Arguments even_odd_neighbors {even odd}.

Arguments Rise {even odd}.
Arguments Fall {even odd}.

Arguments next_state {even odd}.

Arguments next_state_o {even odd}.
Arguments next_state_e {even odd}.
Arguments even_state {even odd P}.
Arguments odd_state {even odd P}.
Arguments sync_eval {even odd}.
Arguments is_enabled {transition}.

(*Arguments fire_tstate {even odd Heven Hodd}.*)

Existing Instance nat_eq_dec.
Existing Instance value_eq_dec.
Existing Instance event_eq_dec.

Arguments async {even odd Heven Hodd}.
Notation "⟨ c , st ⟩⊢ t ↓ l ↦{ O } v" := (async c st t l O v)
          (no associativity, at level 90).
(* end hide *)

(** * Tactics *)
Module Circuit_Tactics.

Lemma neighbor_neq : forall {even odd} (c : circuit even odd) l l',
    neighbor c l l' -> l <> l'.
Proof.
  intros even odd c l l' H.
  destruct H; discriminate.
Qed.

(** Use [find_event_contradiction] when there is a hypothesis that contains a
contradiction regarding events. *)
Ltac find_event_contradiction :=
  try match goal with
      | [ H : Fall _ = Rise _ |- _ ] => inversion H
      | [ H : Fall (Even _) = Fall (Odd _) |- _ ] => inversion H
      | [ H : Fall (Odd _) = Fall (Even _) |- _ ] => inversion H
      | [ H : Rise _ = Fall _ |- _ ] => inversion H
      | [ H : Rise (Even _) = Rise (Odd _) |- _ ] => inversion H
      | [ H : Rise (Odd _) = Rise (Even _) |- _ ] => inversion H
      | [ H : neighbor _ ?l ?l'
        , H' : Rise _ = Rise _ |- _ ] =>
        absurd (l = l'); [ apply (neighbor_neq _ _ _ H) | inversion H'; auto ]
      | [ H : neighbor _ ?l ?l'
        , H' : Fall _ = Fall _ |- _ ] =>
        absurd (l = l'); [ apply (neighbor_neq _ _ _ H) | inversion H'; auto ]
      | [ H : neighbor _ (Odd _ ) (Odd _) |- _ ] => inversion H
      | [ H : neighbor _ (Even _ ) (Even _) |- _ ] => inversion H
      end.

(** Specialize hypotheses generated by is_enabled constraints (instantiated by
the tactic [get_enabled_constraints] in [RiseDecoupled.v] and [FallDecoupled.v] *)
Ltac specialize_enabled_constraints :=
  repeat match goal with
  | [ HEO : In (_,_) (even_odd_neighbors _)
    , H : forall x, In _ (even_odd_neighbors ?c) -> _
    |- _] => specialize (H _ HEO)
  | [ HEO : In (_,_) (even_odd_neighbors _)
    , H : forall x y, In _ (even_odd_neighbors _) -> _
    |- _] => specialize (H _ _ HEO)
  | [ HOE : In (_,_) (odd_even_neighbors _)
    , H : forall x, In _ (odd_even_neighbors _) -> _
    |- _] => specialize (H _ HOE)
  | [ HOE : In (_,_) (odd_even_neighbors _)
    , H : forall x y, In _ (odd_even_neighbors _) -> _
    |- _] => specialize (H _ _ HOE)

  | [ Hneighbor : neighbor _ ?l ?l'
    , H' : forall x, neighbor _ ?l x -> _
    |- _ ] => specialize (H' l' Hneighbor)
  | [ Hneighbor : neighbor _ ?l ?l'
    , H' : forall x, neighbor _ x ?l' -> _
    |- _ ] => specialize (H' l Hneighbor)
  | [ Hneighbor : neighbor _ ?l ?l'
    , H' : forall x y, neighbor _ _ _ -> _
    |- _ ] => specialize (H' _ _ Hneighbor)

  | [ O : ?odd , HO : forall (o' : ?odd), _ = _ |- _ ] => specialize (HO O)
  | [ E : ?even , HE : forall (e' : ?even), _ = _ |- _ ] => specialize (HE E)
  | [ O : ?odd , HO : forall (o' : ?odd), _ < _ |- _ ] => specialize (HO O)
  | [ E : ?even , HE : forall (e' : ?even), _ < _ |- _ ] => specialize (HE E)
  | [ O : ?odd , Hl : forall (l : latch _ _), _ = _ |- _ ] => specialize (Hl (Odd O))
  | [ E : ?even , Hl : forall (l : latch _ _), _ = _ |- _ ] => specialize (Hl (Even E))
  | [ l : latch _ _ , Hl : forall (l : latch _ _), _ = _ |- _ ] => specialize (Hl l)
  | [ O : ?odd , Hl : forall (l : latch _ _), _ < _ |- _ ] => specialize (Hl (Odd O))
  | [ E : ?even , Hl : forall (l : latch _ _), _ < _ |- _ ] => specialize (Hl (Even E))
  | [ l : latch _ _ , Hl : forall (l : latch _ _), _ < _ |- _ ] => specialize (Hl l)

  | [ H : ?P, H' : ?P -> _ |- _ ] => specialize (H' H)
  end.

(** [inversion_neighbors] can be used when you have a hypothesis of the form
[neighbor c l1 l2] and you want to do case analysis on whether the neighbors are
even-odd or odd-even *)
Ltac inversion_neighbors :=
  match goal with
  | [ H : neighbor _ _ _ |- _ ] =>
    inversion H; subst
  end;
  repeat match goal with
  | [ H : In (_, _) (odd_even_neighbors _) |- _ ] => simpl in H
  | [ H : In (_, _) (even_odd_neighbors _) |- _ ] => simpl in H
  | [ H : (_,_) = (_,_) \/ _ |- _ ] => destruct H as [H | H]; [inversion H; subst | ]
  | [ H : False |- _ ] => contradiction
  end.

  (* Solve goals of the form ⟨c,st⟩⊢ t ↓ l ↦ v *)
  Ltac async_constructor :=
    match goal with
    | [ |- ⟨_,_⟩⊢ _ ↓ _ ↦{ Transparent } _] =>
      eapply async_transparent;
        [reflexivity | intros l' Hl'; inversion_neighbors; clear Hl'; simpl | ]
    | [ |- ⟨_,_⟩⊢ _ ▶ Fall ?l ↓ ?l ↦{ Opaque } _ ] =>
      eapply async_opaque_fall;
        [reflexivity | intros l' Hl'; inversion_neighbors; clear Hl'; simpl | ]
    | [ |- ⟨_,_⟩⊢ _ ▶ _ ↓ _ ↦{ Opaque } _ ] =>
      eapply async_opaque; [try discriminate | reflexivity | ]
    | [ |- ⟨_,_⟩⊢ t_empty ↓ _ ↦{ Opaque } _ ] =>
      apply async_nil; reflexivity
    end.
End Circuit_Tactics.


(* From lfind Require Import LFind. *)
Unset Printing Notations.
Set Printing Implicit.
Require Import Nat Arith.

Fixpoint plus (n1 : nat) (n2 : nat) : nat :=
  match n1 with
  | O => n2
  | S n1' => S (plus n1' n2)
  end.

Inductive lst : Type :=
  | Nil : lst
  | Cons : nat -> lst -> lst.

Fixpoint len (l : lst) : nat :=
  match l with
  | Nil => 0
  | Cons x y => plus 1 (len y)
  end.

Fixpoint append (l1 : lst) (l2 : lst) : lst :=
  match l1 with
  | Nil => l2
  | Cons x y => Cons x (append y l2)
  end.

Fixpoint rev (l : lst) : lst :=
  match l with
  | Nil => Nil
  | Cons x y => append (rev y) (Cons x Nil)
  end.

Lemma len_append : forall x y : lst, len (append x y) < S (plus (len x) (len y)).
Proof.
  intros.
  induction x.
  - simpl. apply le_refl.
  - simpl. apply le_n_S. assumption.
Qed.

Theorem len_rev : forall x : lst, len (rev x) < S (len x).
Proof.
  intros.
  induction x.
  - simpl. apply le_refl.
  - simpl. lfind.
Admitted.


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

 Enriched monads

 In this file, we define the basic notions for enriched monads. More
 specifically, we define enrichments of monads and we define enriched
 monads.

 Contents
 1. Enrichments of monads
 2. Enriched monads

 **********************************************************************)
Require Import UniMath.Foundations.All.
Require Import UniMath.MoreFoundations.All.
Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.Core.NaturalTransformations.
Require Import UniMath.CategoryTheory.Monads.Monads.
Require Import UniMath.CategoryTheory.EnrichedCats.Enrichment.
Require Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.
Require Import UniMath.CategoryTheory.EnrichedCats.EnrichmentTransformation.
Require Import UniMath.CategoryTheory.Monoidal.Categories.

Local Open Scope cat.
Local Open Scope moncat.

(**
 1. Enrichments of monads
 *)
Definition monad_enrichment
           {V : monoidal_cat}
           {C : category}
           (E : enrichment C V)
           (M : Monad C)
  : UU
  := ∑ (EM : functor_enrichment M E E),
     nat_trans_enrichment (η M) (functor_id_enrichment _) EM
     ×
     nat_trans_enrichment (μ M) (functor_comp_enrichment EM EM) EM.

Coercion endo_of_monad_enrichment
         {V : monoidal_cat}
         {C : category}
         {E : enrichment C V}
         {M : Monad C}
         (EM : monad_enrichment E M)
  : functor_enrichment M E E
  := pr1 EM.

Definition unit_of_monad_enrichment
           {V : monoidal_cat}
           {C : category}
           {E : enrichment C V}
           {M : Monad C}
           (EM : monad_enrichment E M)
  : nat_trans_enrichment (η M) (functor_id_enrichment _) EM
  := pr12 EM.

Definition mu_of_monad_enrichment
           {V : monoidal_cat}
           {C : category}
           {E : enrichment C V}
           {M : Monad C}
           (EM : monad_enrichment E M)
  : nat_trans_enrichment (μ M) (functor_comp_enrichment EM EM) EM
  := pr22 EM.

(**
 2. Enriched monads
 *)
Definition enriched_monad
           {V : monoidal_cat}
           {C : category}
           (E : enrichment C V)
  : UU
  := ∑ (M : Monad C), monad_enrichment E M.

Coercion enriched_monad_to_monad
         {V : monoidal_cat}
         {C : category}
         {E : enrichment C V}
         (M : enriched_monad E)
  : Monad C
  := pr1 M.

Definition enriched_monad_enrichment
           {V : monoidal_cat}
           {C : category}
           {E : enrichment C V}
           (M : enriched_monad E)
  : monad_enrichment E M
  := pr2 M.


Module first.
  Polymorphic Record BAR (A:Type) :=
  { foo: A->Prop; bar: forall (x y: A), foo x -> foo y}.

Section A.
Context {A:Type}.

Set Printing Universes.

Hint Resolve bar.
Goal forall (P:BAR A) x y, foo _ P x -> foo _ P y.
intros.
eauto.
Qed.
End A.
End first.

Module firstbest.
  Polymorphic Record BAR (A:Type) :=
  { foo: A->Prop; bar: forall (x y: A), foo x -> foo y}.

Section A.
Context {A:Type}.

Set Printing Universes.

Polymorphic Hint Resolve bar.
Goal forall (P:BAR A) x y, foo _ P x -> foo _ P y.
intros.
eauto.
Qed.
End A.
End firstbest.

Module second.
Axiom foo: Set.
Axiom foo': Set.

Polymorphic Record BAR (A:Type) :=
  { bar: foo' -> foo}.
Set Printing Universes.

Lemma baz@{i}: forall (P:BAR@{Set} nat), foo' -> foo.
  eauto using bar.
Qed.
End second.


Require Import Overture.
Set Universe Polymorphism.

Definition EapD {A:Type} {B:A->Type} (f:forall a:A, B a) {x y:A} (p:x≡y):
  p E# (f x) ≡ f y
  :=
  match p with refl => refl end.
Arguments EapD {A%type_scope B} f {x y} p%eq_scope : simpl nomatch.

Definition Etransport_Vp {A: Type} (P: A -> Type) {x y: A} (p: x ≡ y) (z: P x)
  : p^E E# p E# z ≡ z.
Proof.
  destruct p; reflexivity.
Defined.

Definition Etransport_compose {A B : Type} {x y : A} (P : B -> Type) (f : A -> B)
           (p : x ≡ y) (z : P (f x)) :
  Etransport (fun x0 : A => P (f x0)) p z ≡ Etransport P (Eap f p) z.
destruct p. reflexivity.
Defined.

Definition eq_sigma {A: Type} (P: A -> Type) {x x': A} {y: P x} {y': P x'}
           (p: x ≡ x') (q: p E# y ≡ y')
  : (x; y) ≡ (x'; y').
Proof.
  destruct p, q; reflexivity.
Defined.

Definition Etransport_sigma' {A B : Type} {C : A -> B -> Type}
           {x1 x2 : A} (p : x1 ≡ x2) yz
: Etransport (fun x => sigT (C x)) p yz ≡
  (yz.1 ; Etransport (fun x => C x yz.1) p yz.2).
Proof.
  destruct p. destruct yz. reflexivity.
Defined.

Definition pr1_eq {A : Type} `{P : A -> Type} {u v : sigT P} (p : u ≡ v)
  : u.1 ≡ v.1
  := Eap pr1 p.

Notation "p ..1E" := (pr1_eq p) (at level 3).

Definition pr2_eq {A : Type} `{P : A -> Type} {u v : sigT P} (p : u ≡ v)
  : p..1E E# u.2 ≡ v.2
  := (Etransport_compose P pr1 p u.2)^E
     E@ (@EapD { x & P x} _ pr2 _ _ p).

Notation "p ..2E" := (pr2_eq p) (at level 3).


Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas32_2e448m2e224m1_16limbs.Synthesis.

(* TODO : change this to field once field isomorphism happens *)
Definition carry :
  { carry : feBW_loose -> feBW_tight
  | forall a, phiBW_tight (carry a) = (phiBW_loose a) }.
Proof.
  Set Ltac Profiling.
  Time synthesize_carry ().
  Show Ltac Profile.
Time Defined.

Print Assumptions carry.


(** * Basics: Functional Programming in Coq *)

(*
   [Admitted] is Coq's "escape hatch" that says accept this definition
   without proof.  We use it to mark the 'holes' in the development
   that should be completed as part of your homework exercises.  In
   practice, [Admitted] is useful when you're incrementally developing
   large proofs.

   As of Coq 8.4 [admit] is in the standard library, but we include
   it here for backwards compatibility.
*)
Definition admit {T: Type} : T.  Admitted.

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

(** The functional programming style brings programming closer to
    mathematics: If a procedure or method has no side effects, then
    pretty much all you need to understand about it is how it maps
    inputs to outputs -- that is, you can think of its behavior as
    just computing a mathematical function.  This is one reason for
    the word "functional" in "functional programming."  This direct
    connection between programs and simple mathematical objects
    supports both sound informal reasoning and formal proofs of
    correctness.

    The other sense in which functional programming is "functional" is
    that it emphasizes the use of functions (or methods) as
    _first-class_ values -- i.e., values that can be passed as
    arguments to other functions, returned as results, stored in data
    structures, etc.  The recognition that functions can be treated as
    data in this way enables a host of useful idioms, as we will see.

    Other common features of functional languages include _algebraic
    data types_ and _pattern matching_, which make it easy to construct
    and manipulate rich data structures, and sophisticated
    _polymorphic type systems_ that support abstraction and code
    reuse.  Coq shares all of these features.
*)

(* ###################################################################### *)
(** * Enumerated Types *)

(** One unusual aspect of Coq is that its set of built-in
    features is _extremely_ small.  For example, instead of providing
    the usual palette of atomic data types (booleans, integers,
    strings, etc.), Coq offers an extremely powerful mechanism for
    defining new data types from scratch -- so powerful that all these
    familiar types arise as instances.

    Naturally, the Coq distribution comes with an extensive standard
    library providing definitions of booleans, numbers, and many
    common data structures like lists and hash tables.  But there is
    nothing magic or primitive about these library definitions: they
    are ordinary user code.

    To see how this works, let's start with a very simple example. *)

(* ###################################################################### *)
(** ** Days of the Week *)

(** The following declaration tells Coq that we are defining
    a new set of data values -- a _type_. *)

Inductive day : Type :=
  | monday : day
  | tuesday : day
  | wednesday : day
  | thursday : day
  | friday : day
  | saturday : day
  | sunday : day.

(** The type is called [day], and its members are [monday],
    [tuesday], etc.  The second through eighth lines of the definition
    can be read "[monday] is a [day], [tuesday] is a [day], etc."

    Having defined [day], we can write functions that operate on
    days. *)

Definition next_weekday (d:day) : day :=
  match d with
  | monday    => tuesday
  | tuesday   => wednesday
  | wednesday => thursday
  | thursday  => friday
  | friday    => monday
  | saturday  => monday
  | sunday    => monday
  end.

(** One thing to note is that the argument and return types of
    this function are explicitly declared.  Like most functional
    programming languages, Coq can often work out these types even if
    they are not given explicitly -- i.e., it performs some _type
    inference_ -- but we'll always include them to make reading
    easier. *)

(** Having defined a function, we should check that it works on
    some examples.  There are actually three different ways to do this
    in Coq.  First, we can use the command [Eval compute] to evaluate a
    compound expression involving [next_weekday].  *)

Eval compute in (next_weekday friday).
   (* ==> monday : day *)
Eval compute in (next_weekday (next_weekday saturday)).
   (* ==> tuesday : day *)

(** If you have a computer handy, now would be an excellent
    moment to fire up the Coq interpreter under your favorite IDE --
    either CoqIde or Proof General -- and try this for yourself.  Load
    this file ([Basics.v]) from the book's accompanying Coq sources,
    find the above example, submit it to Coq, and observe the
    result. *)

(** The keyword [compute] tells Coq precisely how to
    evaluate the expression we give it.  For the moment, [compute] is
    the only one we'll need; later on we'll see some alternatives that
    are sometimes useful. *)

(** Second, we can record what we _expect_ the result to be in
    the form of a Coq example: *)

Example test_next_weekday:
  (next_weekday (next_weekday saturday)) = tuesday.

(** This declaration does two things: it makes an
    assertion (that the second weekday after [saturday] is [tuesday]),
    and it gives the assertion a name that can be used to refer to it
    later. *)
(** Having made the assertion, we can also ask Coq to verify it,
    like this: *)

Proof. simpl. reflexivity.  Qed.

(** The details are not important for now (we'll come back to
    them in a bit), but essentially this can be read as "The assertion
    we've just made can be proved by observing that both sides of the
    equality evaluate to the same thing, after some simplification." *)

(** Third, we can ask Coq to "extract," from a [Definition], a
    program in some other, more conventional, programming
    language (OCaml, Scheme, or Haskell) with a high-performance
    compiler.  This facility is very interesting, since it gives us a
    way to construct _fully certified_ programs in mainstream
    languages.  Indeed, this is one of the main uses for which Coq was
    developed.  We'll come back to this topic in later chapters.
    More information can also be found in the Coq'Art book by Bertot
    and Casteran, as well as the Coq reference manual. *)

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

(** In a similar way, we can define the type [bool] of booleans,
    with members [true] and [false]. *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

(** Although we are rolling our own booleans here for the sake
    of building up everything from scratch, Coq does, of course,
    provide a default implementation of the booleans in its standard
    library, together with a multitude of useful functions and
    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library
    documentation if you're interested.)  Whenever possible, we'll
    name our own definitions and theorems so that they exactly
    coincide with the ones in the standard library. *)

(** Functions over booleans can be defined in the same way as
    above: *)

Definition negb (b:bool) : bool :=
  match b with
  | true => false
  | false => true
  end.

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Definition orb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => true
  | false => b2
  end.

(** The last two illustrate the syntax for multi-argument
    function definitions. *)

(** The following four "unit tests" constitute a complete
    specification -- a truth table -- for the [orb] function: *)

Example test_orb1:  (orb true  false) = true.
Proof. reflexivity.  Qed.
Example test_orb2:  (orb false false) = false.
Proof. reflexivity.  Qed.
Example test_orb3:  (orb false true)  = true.
Proof. reflexivity.  Qed.
Example test_orb4:  (orb true  true)  = true.
Proof. reflexivity.  Qed.

(** (Note that we've dropped the [simpl] in the proofs.  It's not
    actually needed because [reflexivity] will automatically perform
    simplification.) *)

(** _A note on notation_: We use square brackets to delimit
    fragments of Coq code in comments in .v files; this convention,
    also used by the [coqdoc] documentation tool, keeps them visually
    separate from the surrounding text.  In the html version of the
    files, these pieces of text appear in a [different font]. *)

(** The values [Admitted] and [admit] can be used to fill
    a hole in an incomplete definition or proof.  We'll use them in the
    following exercises.  In general, your job in the exercises is
    to replace [admit] or [Admitted] with real definitions or proofs. *)

(** **** Exercise: 1 star (nandb) *)
(** Complete the definition of the following function, then make
    sure that the [Example] assertions below can each be verified by
    Coq.  *)

(** This function should return [true] if either or both of
    its inputs are [false]. *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  (* FILL IN HERE *) admit.

(** Remove "[Admitted.]" and fill in each proof with
    "[Proof. reflexivity. Qed.]" *)

Example test_nandb1:               (nandb true false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb2:               (nandb false false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb3:               (nandb false true) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb4:               (nandb true true) = false.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star (andb3) *)
(** Do the same for the [andb3] function below. This function should
    return [true] when all of its inputs are [true], and [false]
    otherwise. *)

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  (* FILL IN HERE *) admit.

Example test_andb31:                 (andb3 true true true) = true.
(* FILL IN HERE *) Admitted.
Example test_andb32:                 (andb3 false true true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb33:                 (andb3 true false true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb34:                 (andb3 true true false) = false.
(* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################################### *)
(** ** Function Types *)

(** The [Check] command causes Coq to print the type of an
    expression.  For example, the type of [negb true] is [bool]. *)

Check true.
(* ===> true : bool *)
Check (negb true).
(* ===> negb true : bool *)

(** Functions like [negb] itself are also data values, just like
    [true] and [false].  Their types are called _function types_, and
    they are written with arrows. *)

Check negb.
(* ===> negb : bool -> bool *)

(** The type of [negb], written [bool -> bool] and pronounced
    "[bool] arrow [bool]," can be read, "Given an input of type
    [bool], this function produces an output of type [bool]."
    Similarly, the type of [andb], written [bool -> bool -> bool], can
    be read, "Given two inputs, both of type [bool], this function
    produces an output of type [bool]." *)

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

(** _Technical digression_: Coq provides a fairly sophisticated
    _module system_, to aid in organizing large developments.  In this
    course we won't need most of its features, but one is useful: If
    we enclose a collection of declarations between [Module X] and
    [End X] markers, then, in the remainder of the file after the
    [End], these definitions will be referred to by names like [X.foo]
    instead of just [foo].  Here, we use this feature to introduce the
    definition of the type [nat] in an inner module so that it does
    not shadow the one from the standard library. *)

Module Playground1.

(** The types we have defined so far are examples of "enumerated
    types": their definitions explicitly enumerate a finite set of
    elements.  A more interesting way of defining a type is to give a
    collection of "inductive rules" describing its elements.  For
    example, we can define the natural numbers as follows: *)

Inductive nat : Type :=
  | O : nat
  | S : nat -> nat.

(** The clauses of this definition can be read:
      - [O] is a natural number (note that this is the letter "[O]," not
        the numeral "[0]").
      - [S] is a "constructor" that takes a natural number and yields
        another one -- that is, if [n] is a natural number, then [S n]
        is too.

    Let's look at this in a little more detail.

    Every inductively defined set ([day], [nat], [bool], etc.) is
    actually a set of _expressions_.  The definition of [nat] says how
    expressions in the set [nat] can be constructed:

    - the expression [O] belongs to the set [nat];
    - if [n] is an expression belonging to the set [nat], then [S n]
      is also an expression belonging to the set [nat]; and
    - expressions formed in these two ways are the only ones belonging
      to the set [nat].

    The same rules apply for our definitions of [day] and [bool]. The
    annotations we used for their constructors are analogous to the
    one for the [O] constructor, and indicate that each of those
    constructors doesn't take any arguments. *)

(** These three conditions are the precise force of the
    [Inductive] declaration.  They imply that the expression [O], the
    expression [S O], the expression [S (S O)], the expression
    [S (S (S O))], and so on all belong to the set [nat], while other
    expressions like [true], [andb true false], and [S (S false)] do
    not.

    We can write simple functions that pattern match on natural
    numbers just as we did above -- for example, the predecessor
    function: *)

Definition pred (n : nat) : nat :=
  match n with
    | O => O
    | S n' => n'
  end.

(** The second branch can be read: "if [n] has the form [S n']
    for some [n'], then return [n']."  *)

End Playground1.

Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n'
  end.

(** Because natural numbers are such a pervasive form of data,
    Coq provides a tiny bit of built-in magic for parsing and printing
    them: ordinary arabic numerals can be used as an alternative to
    the "unary" notation defined by the constructors [S] and [O].  Coq
    prints numbers in arabic form by default: *)

Check (S (S (S (S O)))).
Eval compute in (minustwo 4).

(** The constructor [S] has the type [nat -> nat], just like the
    functions [minustwo] and [pred]: *)

Check S.
Check pred.
Check minustwo.

(** These are all things that can be applied to a number to yield a
    number.  However, there is a fundamental difference: functions
    like [pred] and [minustwo] come with _computation rules_ -- e.g.,
    the definition of [pred] says that [pred 2] can be simplified to
    [1] -- while the definition of [S] has no such behavior attached.
    Although it is like a function in the sense that it can be applied
    to an argument, it does not _do_ anything at all! *)

(** For most function definitions over numbers, pure pattern
    matching is not enough: we also need recursion.  For example, to
    check that a number [n] is even, we may need to recursively check
    whether [n-2] is even.  To write such functions, we use the
    keyword [Fixpoint]. *)

Fixpoint evenb (n:nat) : bool :=
  match n with
  | O        => true
  | S O      => false
  | S (S n') => evenb n'
  end.

(** We can define [oddb] by a similar [Fixpoint] declaration, but here
    is a simpler definition that will be a bit easier to work with: *)

Definition oddb (n:nat) : bool   :=   negb (evenb n).

Example test_oddb1:    (oddb (S O)) = true.
Proof. reflexivity.  Qed.
Example test_oddb2:    (oddb (S (S (S (S O))))) = false.
Proof. reflexivity.  Qed.

(** Naturally, we can also define multi-argument functions by
    recursion.  (Once again, we use a module to avoid polluting the
    namespace.) *)

Module Playground2.

Fixpoint plus (n : nat) (m : nat) : nat :=
  match n with
    | O => m
    | S n' => S (plus n' m)
  end.

(** Adding three to two now gives us five, as we'd expect. *)

Eval compute in (plus (S (S (S O))) (S (S O))).

(** The simplification that Coq performs to reach this conclusion can
    be visualized as follows: *)

(*  [plus (S (S (S O))) (S (S O))]
==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]
==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]
==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]
==> [S (S (S (S (S O))))]          by the first clause of the [match]
*)

(** As a notational convenience, if two or more arguments have
    the same type, they can be written together.  In the following
    definition, [(n m : nat)] means just the same as if we had written
    [(n : nat) (m : nat)]. *)

Fixpoint mult (n m : nat) : nat :=
  match n with
    | O => O
    | S n' => plus m (mult n' m)
  end.

Example test_mult1: (mult 3 3) = 9.
Proof. reflexivity.  Qed.

(** You can match two expressions at once by putting a comma
    between them: *)

Fixpoint minus (n m:nat) : nat :=
  match n, m with
  | O   , _    => O
  | S _ , O    => n
  | S n', S m' => minus n' m'
  end.

(** The _ in the first line is a _wildcard pattern_.  Writing _ in a
    pattern is the same as writing some variable that doesn't get used
    on the right-hand side.  This avoids the need to invent a bogus
    variable name. *)

End Playground2.

Fixpoint exp (base power : nat) : nat :=
  match power with
    | O => S O
    | S p => mult base (exp base p)
  end.

(** **** Exercise: 1 star (factorial) *)
(** Recall the standard factorial function:
<<
    factorial(0)  =  1
    factorial(n)  =  n * factorial(n-1)     (if n>0)
>>
    Translate this into Coq. *)

Fixpoint factorial (n:nat) : nat :=
(* FILL IN HERE *) admit.

Example test_factorial1:          (factorial 3) = 6.
(* FILL IN HERE *) Admitted.
Example test_factorial2:          (factorial 5) = (mult 10 12).
(* FILL IN HERE *) Admitted.
(** [] *)

(** We can make numerical expressions a little easier to read and
    write by introducing "notations" for addition, multiplication, and
    subtraction. *)

Notation "x + y" := (plus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x - y" := (minus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x * y" := (mult x y)
                       (at level 40, left associativity)
                       : nat_scope.

Check ((0 + 1) + 1).

(** (The [level], [associativity], and [nat_scope] annotations
   control how these notations are treated by Coq's parser.  The
   details are not important, but interested readers can refer to the
   "More on Notation" subsection in the "Optional Material" section at
   the end of this chapter.) *)

(** Note that these do not change the definitions we've already
    made: they are simply instructions to the Coq parser to accept [x
    + y] in place of [plus x y] and, conversely, to the Coq
    pretty-printer to display [plus x y] as [x + y]. *)

(** When we say that Coq comes with nothing built-in, we really
    mean it: even equality testing for numbers is a user-defined
    operation! *)
(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,
    yielding a [b]oolean.  Note the use of nested [match]es (we could
    also have used a simultaneous match, as we did in [minus].)  *)

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

(** Similarly, the [ble_nat] function tests [nat]ural numbers for
    [l]ess-or-[e]qual, yielding a [b]oolean. *)

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

Example test_ble_nat1:             (ble_nat 2 2) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat2:             (ble_nat 2 4) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat3:             (ble_nat 4 2) = false.
Proof. reflexivity.  Qed.

(** **** Exercise: 2 stars (blt_nat) *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for
    this one, define it in terms of a previously defined function.

    Note: If you have trouble with the [simpl] tactic, try using
    [compute], which is like [simpl] on steroids.  However, there is a
    simple, elegant solution for which [simpl] suffices. *)

Definition blt_nat (n m : nat) : bool :=
  (* FILL IN HERE *) admit.

Example test_blt_nat1:             (blt_nat 2 2) = false.
(* FILL IN HERE *) Admitted.
Example test_blt_nat2:             (blt_nat 2 4) = true.
(* FILL IN HERE *) Admitted.
Example test_blt_nat3:             (blt_nat 4 2) = false.
(* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################################### *)
(** * Proof by Simplification *)

(** Now that we've defined a few datatypes and functions, let's
    turn to the question of how to state and prove properties of their
    behavior.  Actually, in a sense, we've already started doing this:
    each [Example] in the previous sections makes a precise claim
    about the behavior of some function on some particular inputs.
    The proofs of these claims were always the same: use [reflexivity]
    to check that both sides of the [=] simplify to identical values.

    (By the way, it will be useful later to know that
    [reflexivity] actually does somewhat more simplification than [simpl]
    does -- for example, it tries "unfolding" defined terms, replacing them with
    their right-hand sides.  The reason for this difference is that,
    when reflexivity succeeds, the whole goal is finished and we don't
    need to look at whatever expanded expressions [reflexivity] has
    found; by contrast, [simpl] is used in situations where we may
    have to read and understand the new goal, so we would not want it
    blindly expanding definitions.)

    The same sort of "proof by simplification" can be used to prove
    more interesting properties as well.  For example, the fact that
    [0] is a "neutral element" for [+] on the left can be proved
    just by observing that [0 + n] reduces to [n] no matter what
    [n] is, a fact that can be read directly off the definition of [plus].*)

Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
  intros n. reflexivity.  Qed.

(** (_Note_: You may notice that the above statement looks
    different in the original source file and the final html output. In Coq
    files, we write the [forall] universal quantifier using the
    "_forall_" reserved identifier. This gets printed as an
    upside-down "A", the familiar symbol used in logic.)  *)

(** The form of this theorem and proof are almost exactly the
    same as the examples above; there are just a few differences.

    First, we've used the keyword [Theorem] instead of
    [Example].  Indeed, the difference is purely a matter of
    style; the keywords [Example] and [Theorem] (and a few others,
    including [Lemma], [Fact], and [Remark]) mean exactly the same
    thing to Coq.

    Secondly, we've added the quantifier [forall n:nat], so that our
    theorem talks about _all_ natural numbers [n].  In order to prove
    theorems of this form, we need to to be able to reason by
    _assuming_ the existence of an arbitrary natural number [n].  This
    is achieved in the proof by [intros n], which moves the quantifier
    from the goal to a "context" of current assumptions. In effect, we
    start the proof by saying "OK, suppose [n] is some arbitrary number."

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to tell Coq how it should check the correctness of some
    claim we are making.  We will see several more tactics in the rest
    of this lecture, and yet more in future lectures. *)

(** Step through these proofs in Coq and notice how the goal and
    context change. *)

Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
  intros n. reflexivity.  Qed.

Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
  intros n. reflexivity.  Qed.

(** The [_l] suffix in the names of these theorems is
    pronounced "on the left." *)

(* ###################################################################### *)
(** * Proof by Rewriting *)

(** Here is a slightly more interesting theorem: *)

Theorem plus_id_example : forall n m:nat,
  n = m ->
  n + n = m + m.

(** Instead of making a completely universal claim about all numbers
    [n] and [m], this theorem talks about a more specialized property
    that only holds when [n = m].  The arrow symbol is pronounced
    "implies."

    As before, we need to be able to reason by assuming the existence
    of some numbers [n] and [m].  We also need to assume the hypothesis
    [n = m]. The [intros] tactic will serve to move all three of these
    from the goal into assumptions in the current context.

    Since [n] and [m] are arbitrary numbers, we can't just use
    simplification to prove this theorem.  Instead, we prove it by
    observing that, if we are assuming [n = m], then we can replace
    [n] with [m] in the goal statement and obtain an equality with the
    same expression on both sides.  The tactic that tells Coq to
    perform this replacement is called [rewrite]. *)

Proof.
  intros n m.   (* move both quantifiers into the context *)
  intros H.     (* move the hypothesis into the context *)
  rewrite -> H. (* Rewrite the goal using the hypothesis *)
  reflexivity.  Qed.

(** The first line of the proof moves the universally quantified
    variables [n] and [m] into the context.  The second moves the
    hypothesis [n = m] into the context and gives it the (arbitrary)
    name [H].  The third tells Coq to rewrite the current goal ([n + n
    = m + m]) by replacing the left side of the equality hypothesis
    [H] with the right side.

    (The arrow symbol in the [rewrite] has nothing to do with
    implication: it tells Coq to apply the rewrite from left to right.
    To rewrite from right to left, you can use [rewrite <-].  Try
    making this change in the above proof and see what difference it
    makes in Coq's behavior.) *)

(** **** Exercise: 1 star (plus_id_exercise) *)
(** Remove "[Admitted.]" and fill in the proof. *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** As we've seen in earlier examples, the [Admitted] command
    tells Coq that we want to skip trying to prove this theorem and
    just accept it as a given.  This can be useful for developing
    longer proofs, since we can state subsidiary facts that we believe
    will be useful for making some larger argument, use [Admitted] to
    accept them on faith for the moment, and continue thinking about
    the larger argument until we are sure it makes sense; then we can
    go back and fill in the proofs we skipped.  Be careful, though:
    every time you say [Admitted] (or [admit]) you are leaving a door
    open for total nonsense to enter Coq's nice, rigorous, formally
    checked world! *)

(** We can also use the [rewrite] tactic with a previously proved
    theorem instead of a hypothesis from the context. *)

Theorem mult_0_plus : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_O_n.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (mult_S_1) *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################################### *)
(** * Proof by Case Analysis *)

(** Of course, not everything can be proved by simple
    calculation: In general, unknown, hypothetical values (arbitrary
    numbers, booleans, lists, etc.) can block the calculation.
    For example, if we try to prove the following fact using the
    [simpl] tactic as above, we get stuck. *)

Theorem plus_1_neq_0_firsttry : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n.
  simpl.  (* does nothing! *)
Abort.

(** The reason for this is that the definitions of both
    [beq_nat] and [+] begin by performing a [match] on their first
    argument.  But here, the first argument to [+] is the unknown
    number [n] and the argument to [beq_nat] is the compound
    expression [n + 1]; neither can be simplified.

    What we need is to be able to consider the possible forms of [n]
    separately.  If [n] is [O], then we can calculate the final result
    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].
    And if [n = S n'] for some [n'], then, although we don't know
    exactly what number [n + 1] yields, we can calculate that, at
    least, it will begin with one [S], and this is enough to calculate
    that, again, [beq_nat (n + 1) 0] will yield [false].

    The tactic that tells Coq to consider, separately, the cases where
    [n = O] and where [n = S n'] is called [destruct]. *)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem as
    proved.  (No special command is needed for moving from one subgoal
    to the other.  When the first subgoal has been proved, it just
    disappears and we are left with the other "in focus.")  In this
    proof, each of the subgoals is easily proved by a single use of
    [reflexivity].

    The annotation "[as [| n']]" is called an _intro pattern_.  It
    tells Coq what variable names to introduce in each subgoal.  In
    general, what goes between the square brackets is a _list_ of
    lists of names, separated by [|].  Here, the first component is
    empty, since the [O] constructor is nullary (it doesn't carry any
    data).  The second component gives a single name, [n'], since [S]
    is a unary constructor.

    The [destruct] tactic can be used with any inductively defined
    datatype.  For example, we use it here to prove that boolean
    negation is involutive -- i.e., that negation is its own
    inverse. *)

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b. destruct b.
    reflexivity.
    reflexivity.  Qed.

(** Note that the [destruct] here has no [as] clause because
    none of the subcases of the [destruct] need to bind any variables,
    so there is no need to specify any names.  (We could also have
    written [as [|]], or [as []].)  In fact, we can omit the [as]
    clause from _any_ [destruct] and Coq will fill in variable names
    automatically.  Although this is convenient, it is arguably bad
    style, since Coq often makes confusing choices of names when left
    to its own devices. *)

(** **** Exercise: 1 star (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################################### *)
(** * More Exercises *)

(** **** Exercise: 2 stars (boolean functions) *)
(** Use the tactics you have learned so far to prove the following
    theorem about boolean functions. *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  (* FILL IN HERE *) Admitted.

(** Now state and prove a theorem [negation_fn_applied_twice] similar
    to the previous one but where the second hypothesis says that the
    function [f] has the property that [f x = negb x].*)

(* FILL IN HERE *)

(** **** Exercise: 2 stars (andb_eq_orb) *)
(** Prove the following theorem.  (You may want to first prove a
    subsidiary lemma or two. Alternatively, remember that you do
    not have to introduce all hypotheses at the same time.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  (* FILL IN HERE *) Admitted.

(** **** Exercise: 3 stars (binary) *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

      - zero,
      - twice a binary number, or
      - one more than twice a binary number.

    (a) First, write an inductive definition of the type [bin]
        corresponding to this description of binary numbers.

    (Hint: Recall that the definition of [nat] from class,
    Inductive nat : Type :=
      | O : nat
      | S : nat -> nat.
    says nothing about what [O] and [S] "mean."  It just says "[O] is
    in the set called [nat], and if [n] is in the set then so is [S
    n]."  The interpretation of [O] as zero and [S] as successor/plus
    one comes from the way that we _use_ [nat] values, by writing
    functions to do things with them, proving things about them, and
    so on.  Your definition of [bin] should be correspondingly simple;
    it is the functions you will write next that will give it
    mathematical meaning.)

    (b) Next, write an increment function for binary numbers, and a
        function to convert binary numbers to unary numbers.

    (c) Write some unit tests for your increment and binary-to-unary
        functions. Notice that incrementing a binary number and
        then converting it to unary should yield the same result as first
        converting it to unary and then incrementing.
*)

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

(* ###################################################################### *)
(** * Optional Material *)

(** ** More on Notation *)

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

(** For each notation-symbol in Coq we can specify its _precedence level_
    and its _associativity_. The precedence level n can be specified by the
    keywords [at level n] and it is helpful to disambiguate
    expressions containing different symbols. The associativity is helpful
    to disambiguate expressions containing more occurrences of the same
    symbol. For example, the parameters specified above for [+] and [*]
    say that the expression [1+2*3*4] is a shorthand for the expression
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.

    Each notation-symbol in Coq is also active in a _notation scope_.
    Coq tries to guess what scope you mean, so when you write [S(O*O)]
    it guesses [nat_scope], but when you write the cartesian
    product (tuple) type [bool*bool] it guesses [type_scope].
    Occasionally you have to help it out with percent-notation by
    writing [(x*y)%nat], and sometimes in Coq's feedback to you it
    will use [%nat] to indicate what scope a notation is in.

    Notation scopes also apply to numeral notation (3,4,5, etc.), so you
    may sometimes see [0%nat] which means [O], or [0%Z] which means the
    Integer zero.
*)

(** ** [Fixpoint]s and Structural Recursion *)

Fixpoint plus' (n : nat) (m : nat) : nat :=
  match n with
    | O => m
    | S n' => S (plus' n' m)
  end.

(** When Coq checks this definition, it notes that [plus'] is
    "decreasing on 1st argument."  What this means is that we are
    performing a _structural recursion_ over the argument [n] -- i.e.,
    that we make recursive calls only on strictly smaller values of
    [n].  This implies that all calls to [plus'] will eventually
    terminate.  Coq demands that some argument of _every_ [Fixpoint]
    definition is "decreasing".

    This requirement is a fundamental feature of Coq's design: In
    particular, it guarantees that every function that can be defined
    in Coq will terminate on all inputs.  However, because Coq's
    "decreasing analysis" is not very sophisticated, it is sometimes
    necessary to write functions in slightly unnatural ways. *)

(** **** Exercise: 2 stars, optional (decreasing) *)
(** To get a concrete sense of this, find a way to write a sensible
    [Fixpoint] definition (of a simple function on numbers, say) that
    _does_ terminate on all inputs, but that Coq will _not_ accept
    because of this restriction. *)

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

(* $Date: 2013-12-03 07:45:41 -0500 (Tue, 03 Dec 2013) $ *)