Require Import Reals Psatz Lra Bool.
From Coquelicot Require Import Continuity
  Derive Hierarchy AutoDerive Rbar Complex RInt Derive_2d Rcomplements.
From Coq Require Import ssreflect ssrfun ssrbool.
Close Scope boolean_if_scope.
Require Import Program.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Set Bullet Behavior "Strict Subproofs".

Open Scope program_scope.
Open Scope general_if_scope.
Require Import helpers.

Section PathConnected .
  Open Scope R.
  Program Definition path_connected {T: UniformSpace} (D: T -> Prop) :=
    forall x y : T,
    D x ->
    D y ->
    exists f : R -> T,
    f 0 = x /\ filterlim f (at_right 0) (locally x) /\
    f 1 = y /\ filterlim f (at_left  1) (locally y) /\
    (forall t, 0 < t < 1 -> continuous f t) /\
    forall t : { t: R | 0 <= t <= 1 }, D (f t).
  Program Definition convex  {T: NormedModule R_AbsRing} (D: T -> Prop) :=
    forall (x y : T) (t : R),
      D x ->
      D y ->
      0 <= t <= 1 ->
    D (plus (scal (1-t) x) ( scal t  y)).

  Lemma convex_ext: forall (T: NormedModule R_AbsRing) (D1 D2: T -> Prop),
    (forall x, D1 x <-> D2 x) -> convex D1 <-> convex D2.
  Proof.
    move => ? D1 D2 ext.
    split; move => H ???;
    [rewrite -!ext | rewrite ! ext]; apply H.
  Qed.

  Lemma cts_all_cts_on:
    forall {T: NormedModule R_AbsRing} (f:R -> T) x y,
    f 0 = x ->
    f 1 = y ->
    (forall t, continuous f t) ->
    filterlim f (at_right 0) (locally x) /\
    filterlim f (at_left  1) (locally y) /\
    (forall t, 0 < t < 1 -> continuous f t).
  Proof.
    move => T f x y f0 f1 cts.
    repeat split; auto.
    - apply: filterlim_filter_le_1.
      apply: filter_le_within.
      rewrite -f0.
      apply cts.
    - apply: filterlim_filter_le_1.
      apply: filter_le_within.
      rewrite -f1.
      apply cts.
  Qed.

  Lemma convex_path_connected {T: NormedModule R_AbsRing} (D: T -> Prop):
    convex D -> path_connected D.
  Proof.
    rewrite /convex /path_connected.
    move => pathD x y Dx Dy.
    pose f := fun t => (plus (scal (1 - t) x) (scal t y)).
    exists f.
    have f0: (f 0 = x) by
      rewrite /f !Rminus_0_r scal_zero_l scal_one plus_zero_r.
    have f1: (f 1 = y) by
      rewrite /f !Rcomplements.Rminus_eq_0 scal_zero_l scal_one plus_zero_l.

    repeat split; auto.
    - apply: filterlim_filter_le_1; first by apply: filter_le_within.
      rewrite -[x in filterlim _ _ (locally x)] f0.
      rewrite -/(continuous _ _) /f.
      auto_cts.
    - apply: filterlim_filter_le_1; first by apply: filter_le_within.
      rewrite -[x in filterlim _ _ (locally x)] f1.
      rewrite -/(continuous _ _) /f.
      auto_cts.
    - move => t _. rewrite /f. auto_cts.
    - move => t. apply pathD; auto.
      case: t; auto.
  Qed.
End PathConnected.

Open Scope fun_scope.
Definition NtoC (n: nat) := RtoC (INR n).

Section Domain.
  Open Scope R.

  Record Domain (D:C -> Prop) := dom {
    open_dom: open D;
    connected_dom: path_connected D;
    dec_D : C -> bool;
    dec_DP : forall z, reflect (D z) (dec_D z);
  }.

  Definition mkDomain D (_:Domain D): Type := {z:C | D z}.

  Coercion mkDomain : Domain >-> Sortclass.
  (** need Program definition here to help coq understand that
      f only occurs in the (D z) case.*)
  Program Definition const_extend {T:Type} {D_set : C -> Prop}
    {D: Domain D_set} (x:T) (f: D -> T) (z: C): T :=
      if dec (dec_D D z)
      then f z
      else x.
  Obligation 1.
    (move => * //=; apply /(dec_DP); eauto).
  Qed.

  Definition dom_irr {T} {D_set} {D:Domain D_set}  (f: D -> T) :=
    forall z h1 h2, f (exist D_set z h1) = f (exist D_set z h2).
  Program Definition const_extend_id_def :=
    forall T D_set (D: Domain D_set) (f: D -> T) (x:T) z (Dz: D_set z) ,
    dom_irr f ->
    const_extend x f z = f z.

  Lemma const_extend_id: const_extend_id_def.
  Proof.
    rewrite /const_extend_id_def /const_extend.
    move => T Ds D f x z + irr.
    case dec => [ eqt | fls Dz].
    - apply irr.
    - contradict fls. move: Dz => /(dec_DP D) => q; rewrite q //=.
  Qed.

  Lemma ODisk_convex: forall r, (0 < r) -> convex (fun z => Cmod z < r).
  Proof.
    rewrite /convex => r rpos x y t Dx Dy tbd.
    case: tbd.
    case => teq1; case => teq2.
    - apply (Rle_lt_trans _ (Cmod (scal (1-t) x) + Cmod (scal t y)) _);
      first by apply Cmod_triangle.
      rewrite ?scal_R_Cmult ?Cmod_mult ?Cmod_R ?Rabs_pos_eq.
      all: nra.
    - rewrite teq2 scal_one Rcomplements.Rminus_eq_0 scal_zero_l plus_zero_l //=.
    - rewrite -teq1 scal_zero_l plus_zero_r Rminus_0_r scal_one //=.
    - rewrite teq2 in teq1. contradict teq1. auto.
  Qed.

  Lemma convex_translate: forall D z,
    convex D -> convex (fun q => D(z - q)%C ).
  Proof.
    move => D z + x y t Dzx Dzy tbd.
    move => /(_ (z - x)%C (z-y)%C t Dzx Dzy tbd).
    set p := (x in D x).
    set q := (x in _ ->  D x).
    have: p = q; last by congruence.
    rewrite {}/p {}/q.
    do 2 unfold_alg.
    simplify_as_R2 RHS.
    simplify_as_R2 LHS.
    f_equal; field_simplify_eq; auto.
  Qed.

  Program Definition BallDom (r: posreal) z:
    Domain (ball_circ z r) :=
  {|
    open_dom := _;
    connected_dom := _ ;
    dec_D := fun z0 => Rlt_dec (Cmod (z0 - z)%C) r;
    dec_DP := _;
  |}.

  Lemma ball_reduce_eps : forall {T: AbsRing} r (x y:T),
    ball x r y -> ball x ((abs (minus y x)+r)/2) y.
  Proof.
    move => T r x y Br.
    rewrite /ball //= /AbsRing_ball //= in Br *.
    lra.
  Qed.

  Obligation 1.
  Proof.
    move => x /ball_reduce_eps Bx.
    have ?:= cond_pos r.
    apply/locally_C.
    pose del := (r - ((abs(minus x z ) + r)/2)).
    have delpos : 0 < del. {
      rewrite /ball //= /AbsRing_ball //= Rplus_comm in Bx.
      rewrite -> Rcomplements.Rminus_lt_0 in Bx.
      rewrite /del.
      field_simplify.
      field_simplify in Bx.
      exact Bx.
    }
    exists (mkposreal del delpos) => y By.
    have -> : pos r = ((abs (minus x z) +r)/2 + del)%R by
      rewrite /del; lra.
    apply: UniformSpace.ax3; rewrite //= .
    - apply: Bx.
    - apply: By.
  Qed.

  Obligation 2.
    apply: convex_path_connected.
    have ?:= cond_pos r.
    have := ODisk_convex (cond_pos r).
    move => /(@convex_translate _ z) //=.
    rewrite /ball //= /AbsRing_ball /abs //= /minus /plus /opp //=.
    under convex_ext => q.
      replace (Cmod (z -q)%C) with (Cmod (q - z)%C).
    over.
    2: auto.

    rewrite /Cmod.
    f_equal.
    simpl.
    nra.
  Qed.

  Obligation 3.
  Proof.
    apply iff_reflect.
    unfold_alg.
    rewrite -/(Cminus _ _).
    split; case (Rlt_dec (Cmod (z0 - z) %C) r) => x; by auto.
  Qed.

End Domain.

Section Holomorphism.

(** the main definition we care about.
    It will turn out this is much stronger than
    just differentiable in two dimensions
    *)
Definition Holo (f g: C -> C) z :=
  is_derive (K:=C_AbsRing) (V:= C_NormedModule) f z (g z).

Definition is_Holo (f: C -> C) z :=
  exists g, Holo f g z.

(** Assuming the derivative is continuous dramatically simplifies
    this whole project. It turns out Holo -> CHolo, but we don't
    prove that here *)
Definition CHolo f f' z :=
  Holo f f' z /\ continuous f' z.

Definition CHolo_on D f := exists f',
  forall z, D z -> CHolo f f' z.

Lemma is_derive_scal_C: forall z k,
  is_derive (K:=C_AbsRing) (fun q => scal k q) z k.
Proof.
  move => z k.
  rewrite /is_derive.
  under ext_filterdiff_glo => x.
    rewrite /scal //= /mult //= Cmult_comm.
  over.
  apply filterdiff_linear .
  apply is_linear_scal_l.
Qed.

Lemma continuous_Cinv: forall (z:C),
  z <> 0 -> continuous (Cinv) z.
Proof.
  move => z z_neq_0.
  have ?: (z.1 * z.1 + z.2 * z.2 <> 0)%R. {
    contradict z_neq_0.
    field_simplify.
    rewrite [LHS]surjective_pairing.
    f_equal; nra.
  }
  rewrite /Cinv /=.
  auto_cts;
  rewrite /Rdiv;
  auto_cts.
  all: try apply: continuous_fst.
  all: try apply: continuous_snd.
  all: try apply: continuous_Rinv.
  all: lra.
Qed.

Open Scope C.
Lemma Holo_mult: forall f g z k,
  Holo f g z -> Holo (fun q => k * (f q)) (fun q => k * (g q)) z.
Proof.
  move => f g z k.
  move => /(filterdiff_scal_r_fct k ).
  have H := Cmult_comm.
  move /(_ H).
  under ext_filterdiff_d => t.
    rewrite scal_assoc.
    have ->: (mult k t = mult t k) by unfold_alg.
    rewrite -scal_assoc.
  over.
  rewrite -/(is_derive _ _ _) /Holo //=.
Qed.

End Holomorphism.

Hint Immediate continuous_Cinv: teardown_leaf.

Section CauchyRiemann.

Definition CauchyRiemann (udx udy vdx vdy: C -> R) z:=
  udx z = vdy z /\
  udy z = (- vdx z)%R
.

Lemma holo_differentiable_pt_lim_imaginary: forall (f:C -> C) x y g,
  Holo f g (x,y) ->
  differentiable_pt_lim (fun x y => (f (x,y)).2) x y (g (x,y)).2 (g (x,y)).1 .
Proof.
  move => f x y g.
  rewrite /is_derive /filterdiff.
  move => [_ /(_ (x,y))] .
  move => /(_ (@is_filter_lim_locally (AbsRing_UniformSpace C_AbsRing) (x,y) )).
  move => + eps.
  have erpos : ( 0 < eps /(sqrt 2)) by apply Rdiv_lt_0_compat;
    [apply (cond_pos eps) | apply Rlt_sqrt2_0 ].
  pose epsr2 := mkposreal (eps/ (sqrt 2)) erpos .
  move => /(_ epsr2) /locally_C [del H].
  exists del => u v uball vball.
  move :H => /(_ (u,v)).
  unfold_alg; rewrite /AbsRing_ball. unfold_alg .
  have Q: (Rabs (u-x) < del /\ Rabs (v-y) < del) by auto.
  move => /(_ Q) {Q}.
  simplify_as_R2 (x in Cmod x <= _).
  set p := (x in Cmod (x,_)).
  set q := (x in Cmod (_,x)).
  set l := (x in Rabs x).
  simplify_as_R2 (x in Rmult _ (Cmod x)).
  have ->: (l = q) by rewrite /l /q; field_simplify_eq.
  move => H.
  apply: Rle_trans.
  apply: Cmod_Rabs_imaginary p _.
  apply: Rle_trans.
  apply H.
  apply (Rle_trans _ (eps * Rmax (Rabs (u-x)) (Rabs (v-y)))); last by right; auto.
  rewrite /Rdiv.
  rewrite Rmult_assoc.
  apply Rmult_le_compat_l; first by left; apply: cond_pos.
  field_simplify .
  apply/Rcomplements.Rle_div_l; first by apply Rlt_sqrt2_0.
  rewrite Rmult_comm.
  apply Cmod_2Rmax.
  apply Rsqr_gt_0_0.
  rewrite Rsqr_sqrt; lra.
Qed.

Lemma holo_differentiable_pt_lim_real: forall (f:C -> C) x y g,
  Holo f g (x,y) ->
  differentiable_pt_lim (fun x y => (f (x,y)).1) x y (g (x,y)).1 (-g (x,y))%C.2 .
Proof.
  Open Scope C.
  move => f x y g.
  move => /(filterdiff_scal_r_fct Ci ).
  have H := Cmult_comm.
  move /(_ H).
  under ext_filterdiff_d => t.
    rewrite scal_assoc.
    have ->: (mult Ci t = mult t Ci) by unfold_alg.
    rewrite -scal_assoc.
  over.
  simpl.
  rewrite -/(is_derive _ _ _).
  rewrite -/(Holo _ (fun z => scal Ci (g z) ) _).
  move /holo_differentiable_pt_lim_imaginary.
  simpl in *.
  simplify_term (x in differentiable_pt_lim _ _ _ x _).
  simplify_term (x in differentiable_pt_lim _ _ _ _ x).
  eapply differentiable_pt_lim_ext.
  exists pos_half => u v _ _ . field_simplify_eq; auto.
Qed.
  Theorem CauchyRiemann_Easy: forall u v g1 g2 z,
    Holo (fun p => (u p, v p)) (fun p => (g1 p, g2 p)) z ->
    Derive (fun t => u (t,z.2)) z.1 = Derive (fun t => v (z.1,t)) z.2 /\
    Derive (fun t => u (z.1,t)) z.2 = Ropp(Derive (fun t => v (t,z.2)) z.1) /\
    g1 z = Derive (fun t => v (z.1,t)) z.2  /\
    g2 z = Derive (fun t => v (t,z.2)) z.1
  .
  Proof.
    move => u v g1 g2 z.
    rewrite [x in Holo _ _ x]surjective_pairing.
    copy.
    move => /holo_differentiable_pt_lim_imaginary /differentiable_pt_lim_is_derive [+ +]
            /holo_differentiable_pt_lim_real /differentiable_pt_lim_is_derive [+ +].
    do 4 move => /is_derive_unique ->.
    rewrite -?surjective_pairing; auto.
  Qed.

  Open Scope R.
  Theorem MVT_along_axis: forall u udx udy z,
    locally z ( fun q =>
      is_derive (fun t => u (t,q.2)) q.1 (udx q)) ->
    locally z ( fun q =>
      is_derive (fun t => u (q.1,t)) q.2 (udy q)) ->
    locally z (fun a =>
      exists c1 c2,
      Rabs(c1 - z.1) <= Rabs (a.1 - z.1) /\
      Rabs(c2 - z.2) <= Rabs (a.2 - z.2) /\
      (u a - u z = udx (c1,z.2) * (a.1 - z.1) +
                   udy (a.1,c2) * (a.2 - z.2)))
  .
  Proof.
    move => u udx udy z.
    move => loc.
    move => {loc} /(filter_and _ _ loc) => loc.

    case: loc => eps_safe safe.

    eexists ?[del] => a [aballz1 aballz2].

    have H': (?del <= eps_safe) by shelve.
    have H: (ball z eps_safe a) by
      split;
      apply: (Rlt_le_trans _ ?del); auto.
    simpl in *.

    (** the key lemma. Hard to factor due to epsilons and deltas.*)
    have axis_mvt:
      forall (f df :R -> R) bd1 bd2 (extend: R -> C),
      let l0 := Rmin bd1 bd2 in
      let r0 := Rmax bd1 bd2 in
      (forall x, Rabs(x-bd1) <= Rabs(bd2-bd1) ->
        Rabs ((extend x).1 - z.1) < eps_safe /\
        Rabs ((extend x).2 - z.2) < eps_safe) ->
      (forall x, ball z eps_safe (extend x) -> is_derive f x (df x)) ->
      exists c:R, l0 <= c <= r0 /\ (f bd2 - f bd1 = df(c)*(bd2 - bd1))%R.
    { move {safe} => f df bd1 bd2 extend l0 r0 ext_lem diffin.
      have: (forall x, l0 <= x <= r0 -> is_derive f x (df x)).
      - simpl in *. move => x /Rabs_le_between_min_max_2 bds.
        apply: (diffin x).
        apply ext_lem.
        auto.
      - rewrite /r0 /l0 => diff_all.
        apply: MVT_gen => x bds.
        + apply diff_all.
          lra.
        + rewrite continuity_pt_filterlim -/(continuous _ _).
          apply: ex_derive_continuous.
          exists (df x).
          by apply diff_all.
    }

    have := axis_mvt (fun q => u(q,z.2)) (fun q => udx(q,z.2))
      z.1 a.1 (fun q => (q,z.2)).
    case.
    { move => ? bds.
      case: H => H1 H2 //=.
      split.
      + rewrite -!/(Rminus _ _) in bds H1 H2 *.
        apply: (Rle_lt_trans _ _ _ bds); auto.
      + simplify_term (x in Rabs x).
        rewrite Rabs_R0; apply cond_pos.
    }
    {
        move => x.
        move: (safe ) => /(_ (x,z.2)) //=.
        tauto.
    }
    move => xi_udx [/Rabs_le_between_min_max_2 xi_udx_bds mvt_udx].

    have := axis_mvt (fun q => u(a.1,q)) (fun q => udy(a.1,q))
      z.2 a.2 (fun q => (a.1,q)).
    case.
    {
        move => ? bds.
        case: H => H1 H2 //=.
        simpl in *; split.
        + rewrite -!/(Rminus _ _) in bds H1 H2 *; auto.
        + simplify_term (x in Rabs x).
          apply: (Rle_lt_trans _ _ _ bds); auto.
    }
    {
        move => y yball.
        move: (safe ) => /(_ (a.1,y)) //=.
        case; first by exact yball.
        tauto.
    }
    move => xi_udy [/Rabs_le_between_min_max_2 xi_udy_bds mvt_udy].

    exists xi_udx, xi_udy; repeat split; auto.

    `Begin eq (u a - u z). {
    | {( u (a.1, a.2) - u (z.1,z.2) )}
      rewrite -!surjective_pairing.
    | {( (_ - u(a.1,z.2)) + (u(a.1,z.2) - _ ) )}
      field_simplify_eq.
    | {( _ + udx (_,z.2) * (a.1 - z.1) )}
      rewrite mvt_udx.
    | {( udy (a.1, _) * (a.2 - z.2) + _ )}
      rewrite mvt_udy.
    `Done.
    }
    lra.

    Grab Existential Variables.
    apply eps_safe.
    reflexivity.
  Qed.

  Local Lemma filter_apply: forall
    {T: UniformSpace}
    {F: ((T-> Prop) -> Prop)}
    {FF: Filter F}
    {P Q : T -> Prop},
    F P -> F (fun x => (P x -> Q x)) -> F Q.
  Proof.
    move => ? F FF P Q FP FPQ.
    have H := filter_and _ _ FP FPQ.
    move: H => /(_ FF).
    apply: filter_imp => x.
    tauto.
  Qed.

  Definition LocallyPartials (u v udx udy vdx vdy: C -> R)  z :=
    locally z ( fun q =>
      is_derive (fun t => u (t,q.2)) q.1 (udx q)) /\
    locally z ( fun q =>
      is_derive (fun t => u (q.1,t)) q.2 (udy q)) /\
    locally z ( fun q =>
      is_derive (fun t => v (t,q.2)) q.1 (vdx q)) /\
    locally z ( fun q =>
      is_derive (fun t => v (q.1,t)) q.2 (vdy q))
    .

  Open Scope C.
  Theorem CauchyRiemann_Hard: forall u v udx udy vdx vdy z,
    LocallyPartials u v udx udy vdx vdy z ->
    udx z = vdy z ->
    (udy z = - vdx z)%R ->
    continuous udx z ->
    continuous udy z ->
    continuous vdx z ->
    continuous vdy z ->
      Holo (fun q => (u q, v q)) (fun q => (vdy q, vdx q)) z
  .
  Proof.
    move => u v udx udy vdx vdy z CR_diffs cr1 cr2.
    move => /filterlim_locally c_udx.
    move => /filterlim_locally c_udy.
    move => /filterlim_locally c_vdx.
    move => /filterlim_locally c_vdy.
    simpl in *.
    case CR_diffs => d_udx.
    case => d_udy.
    case => d_vdx.
    move => d_vdy.
    rewrite /Holo /is_derive /filterdiff.
    split; first by apply is_linear_scal_l.
    move => + /is_filter_lim_locally_unique <- eps.
    move => _.
    simpl in *.
    apply/locally_C.
    apply: (filter_apply (MVT_along_axis d_udx d_udy)).
    apply: (filter_apply (MVT_along_axis d_vdx d_vdy)).
    pose eps4 := pos_div_2 (pos_div_2 eps).
    move => {d_udx d_udy d_vdx d_vdy }.
    move: c_udx => /(_ eps4).
    move: c_udy => /(_ eps4).
    move: c_vdx => /(_ eps4).
    move: c_vdy => /(_ eps4).
    move => cts.
    do 3 move => {cts} /(filter_and _ _ cts) => cts.
    move: cts => [del] .
    copy.
    move => cr_eqs cts.

    exists del => a aballz .
    simplify_as_R2 (x in norm (minus x _ ) ); simpl.
    rewrite -?/(Rminus _ _).
    move => [c1 [c2 [c1_bd [c2_bd -> ]]]].
    move => [c3 [c4 [c3_bd [c4_bd -> ]]]].

    Open Scope R.
    rewrite /ball //= /prod_ball //= /ball //= /AbsRing_ball /abs //=
    /minus //= /opp /plus //= -2!/(Rminus _ _) in aballz.
    case: aballz => dx_del dy_del.
    set p := (x in norm (minus x _ ) ).
    set dx := (a.1 - z.1) in p c1_bd c3_bd dx_del *.
    set dy := (a.2 - z.2) in p c2_bd c4_bd dy_del *.
    set dz := minus a z in p *.
    `Begin eq p. { rewrite /p.

    | {( ((udx z*dx + udy z*dy + (udx (c3,z.2) - udx z) *dx +
           (udy (a.1,c4) - udy z) *dy) ,_)  )}
      f_equal; field_simplify;
      rewrite {1}Rmult_comm; f_equal;
      rewrite Rmult_comm.

    | {( (_, (vdx z*dx + vdy z*dy + (vdx (c1,z.2) - vdx z) *dx +
           (vdy (a.1,c2) - vdy z) *dy))  )}
      f_equal; field_simplify;
      rewrite {1}Rmult_comm; f_equal;
      rewrite Rmult_comm.
    | {( Cplus (udx z *dx + udy z * dy, vdx z * dx + vdy z * dy) (_,_) )}
      rewrite /Cplus;
      simpl;
      f_equal;
      rewrite 3!Rplus_assoc;
      do 2 apply (Rplus_eq_compat_l).

    | {( Cplus (vdy z * dx + (-vdx z * dy), _) (_,_) )}
      rewrite {1}cr1 {1}cr2.

    | {( dz * (vdy z , vdx z)%R + (_,_) )%C}
      f_equal; rewrite /dz /dx /dy;
      simplify_as_R2 LHS;
      simplify_as_R2 RHS;
      unfold_alg;
      f_equal;
      field_simplify.
    `Done.
    }
    move => -> {p}.
    unfold_alg.
    rewrite -?/(Cminus _ _).
    rewrite Cplus_comm /dz.
    do 2 unfold_alg.
    simplify_as_R2 (x in Cmod x).

    set p := (x in x <= _).
    `Begin Rle p. { rewrite /p.
    | {(  Rabs _ + Rabs _ )}
      apply Cmod_Rabs_plus.
    | {(  (Rabs (_ - _) + Rabs ( _ - _)) + _ )}
      apply Rplus_le_compat_r;
      apply: Rle_trans;last (by apply Rabs_triang);
      rewrite -[x in _ <= Rabs x]Rplus_assoc -/(Rminus _ _).

    | {(  _ + _ + Rabs (_ - _) + Rabs (_ - _) )}
       rewrite !Rplus_assoc;
       do 2 apply Rplus_le_compat_l;
       rewrite -Rplus_assoc;
       apply: Rle_trans;last (by apply Rabs_triang);
       rewrite /Rminus -[x in _ <= Rabs x ]Rplus_assoc.

    | {(  _ * _ dx + _ * _ dy + _ * _ dx + _ * _ dy  )}
      rewrite -?Rmult_minus_distr_r !Rabs_mult.
    | {(  _ + _ + _ + _ * Cmod dz   )}
       apply Rplus_le_compat_l;
       apply Rmult_le_compat_l; first (by apply Rabs_pos);
       apply Cmod_Rabs_imaginary.
    | {(  _ + _ + _ * Cmod dz + _   )}
       apply Rplus_le_compat_r;
       rewrite !Rplus_assoc;
       do 2 apply Rplus_le_compat_l;
       apply Rmult_le_compat_l; first (by apply Rabs_pos);
       apply Cmod_Rabs_real.
    | {(  _ + _ * Cmod dz + _ + _   )}
       do 2 apply Rplus_le_compat_r.
       apply Rplus_le_compat_l.
       apply Rmult_le_compat_l; first (by apply Rabs_pos).
       apply Cmod_Rabs_imaginary.
    | {(   _ * Cmod dz + _ + _ + _  )}
       do 3 apply Rplus_le_compat_r.
       apply Rmult_le_compat_l; first (by apply Rabs_pos).
       apply Cmod_Rabs_real.
    | {(   (_ + _ + _ + _)* Cmod dz )}
      idtac;
      field_simplify;
      rewrite Rmult_comm.
    `Done.
    }
    move => H.
    apply: Rle_trans; first apply H.
    apply Rmult_le_compat_r; first by apply Cmod_ge_0.

    move: cts; do 3 copy;
    rewrite /ball //=
      /AbsRing_ball //= /abs //= /prod_ball
      /ball//= /AbsRing_ball / abs //=.
    unfold_alg.
    move =>
    /(_ (c3,z.2)) cts_udx
    /(_ (a.1,c4)) cts_udy
    /(_ (c1,z.2)) cts_vdx
    /(_ (a.1,c2)) cts_vdy.
    rewrite -!/(Rminus _ _) in cts_udx cts_udy cts_vdx cts_vdy.
    simpl in *.
    rewrite {H}/p {p}.
    set p := (x in x <= _).
    `Begin Rle p. { rewrite /p.
    | {(  _ + _ + _ + eps/2/2   )}
      apply Rplus_le_compat_l;
      left;
      apply cts_vdy;
      split; [ | apply: (Rle_lt_trans _ _ _ c2_bd)]; auto.
    | {(  _ + _ + eps/2/2 + _   )}
      apply Rplus_le_compat_r;
      apply Rplus_le_compat_l;
      left;
      apply cts_vdx;
      split; [ apply: (Rle_lt_trans _ _ _ c1_bd); auto | ];
      rewrite Rminus_eq_0 Rabs_R0; apply: cond_pos.
    | {(  _ + eps/2/2 + _ + _   )}
      do 2 apply Rplus_le_compat_r;
      apply Rplus_le_compat_l.
      left.
      apply cts_udy;
      split; [ apply: dx_del | apply: (Rle_lt_trans _ _ _ c4_bd); auto ].
    | {(  eps/2/2 + _ + _ + _   )}
      do 3 apply Rplus_le_compat_r.
      left.
      apply cts_udx.
      split; [ apply: (Rle_lt_trans _ _ _ c3_bd); auto | ].
      rewrite Rminus_eq_0 Rabs_R0; apply: cond_pos.
    `Done.
    }
    move => H.
    lra.
  Qed.
End CauchyRiemann.

Section CHoloTeardown.
(** Surprisingly, this is the Cauchy riemann equations are
    the easist way to prove Cinv is holomorphic right now *)
Lemma holo_inv : forall (z: C),
  (z <> 0)%C -> (Holo Cinv (fun q => -1/(q * q)) z)%C.
Proof.
  move => z neq_0.
  have zb : 0 < Rmax (Rabs z.1) (Rabs z.2). {
    destruct z; simpl.
    destruct (Req_dec 0 r);
    destruct (Req_dec 0 r0).
    - contradict neq_0; subst; auto.
    - subst. rewrite Rmax_right.
      + apply Rabs_pos_lt; auto.
      + rewrite Rabs_R0; apply Rabs_pos.
    - subst. rewrite Rmax_left.
      + apply Rabs_pos_lt; auto.
      + rewrite Rabs_R0; apply Rabs_pos.
    - apply (@Rmax_case (Rabs r) (Rabs r0) (fun q => 0 < q));
        apply Rabs_pos_lt; auto.
  }
  pose del := (mkposreal _ zb).
  have ball_neq_0: forall y, ball z del y -> (y.1 * y.1 + y.2 * y.2 <> 0)%R. {
    move => y ybd.
    copy => /Rplus_sqr_eq_0_l y1.
    rewrite Rplus_comm.
    move => /Rplus_sqr_eq_0_l y2.
    have: y = (0,0); first by rewrite [LHS]surjective_pairing y1 y2.
    move => ?; subst.
    move: ybd.
    do 2 rewrite /ball /= /prod_ball /= /AbsRing_ball /= .
    unfold_alg.
    rewrite ?Rminus_0_l ?Rabs_Ropp.
    destruct (Rlt_dec (Rabs z.1) (Rabs z.2));
    [rewrite ?Rmax_right| rewrite ?Rmax_left]; lra.

  }
  have ball_pows_0: forall y, ball z del y ->
       ( 0 < y.1 ^ 4 + 2 * y.1 ^ 2 * y.2 ^ 2 + y.2 ^ 4)%R . {
    move => y zbd.
    set p := (x in _ < x).
    replace p with ((y.1 * y.1 + y.2 * y.2)^2); last by
      rewrite /p; lra.
    apply pow2_gt_0.
    apply ball_neq_0.
    auto.
  }
  apply: CauchyRiemann_Hard; simpl.
  1:{ rewrite /LocallyPartials. repeat split;
    ( exists del => y yb;
      simpl in *;
      auto_derive;
      rewrite ?Rmult_0_l ?Rminus_0_l ?Rmult_1_l
              ?Rmult_1_r ?Rminus_0_r ?Rplus_0_r //=;
      repeat split; try by apply: ball_neq_0);
      field_simplify_eq; auto; repeat split;
      try by apply: ball_neq_0.
    + apply: Rlt_0_neq_0. field_simplify. apply ball_pows_0; auto.
    + apply: Rlt_0_neq_0. field_simplify. apply ball_pows_0; auto.
  }
  1,2: simpl; field_simplify_eq; auto;
    split;
    [ (apply: Rlt_0_neq_0; field_simplify);
      apply ball_pows_0; apply ball_center
    |  apply: ball_neq_0; apply ball_center
    ].
  all: auto_cts.
  all: apply: continuous_Rinv.
  all: try (now apply ball_neq_0; apply ball_center);
    try (now apply: Rlt_0_neq_0; field_simplify; apply ball_pows_0;
             apply ball_center).
Qed.

Lemma CHolo_subset: forall P Q f,
  (forall z, P z -> Q z) ->
  CHolo_on Q f ->
  CHolo_on P f.
Proof.
  move => P Q f sub [f' holo].
  exists f' => z Pz.
  apply holo.
  apply sub.
  auto.
Qed.

Open Scope C.
Lemma CHolo_on_plus: forall D f g,
  CHolo_on D f ->
  CHolo_on D g ->
  CHolo_on D (fun z => f z + g z )
.
Proof.
  move => D f g [f' fholo] [g' gholo].
  exists (fun z => f' z  + g' z) => z Dz.
  split.
  - apply: is_derive_plus.
    + apply fholo; auto.
    + apply gholo; auto.
  - auto_cts.
    + apply fholo; auto.
    + apply gholo; auto.
Qed.

Lemma CHolo_on_minus: forall D f g,
  CHolo_on D f ->
  CHolo_on D g ->
  CHolo_on D (fun z => f z - g z )
.
Proof.
  move => D f g [f' fholo] [g' gholo].
  exists (fun z => f' z  - g' z) => z Dz.
  split.
  - apply: is_derive_minus.
    + apply fholo; auto.
    + apply gholo; auto.
  - auto_cts.
    + apply fholo; auto.
    + apply gholo; auto.
Qed.

Lemma CHolo_on_opp: forall D f,
  CHolo_on D f ->
  CHolo_on D (fun z => - f z)
.
Proof.
  move => D f [f' fholo].
  exists (fun z => - f' z) => z Dz.
  split.
  - apply: is_derive_opp.
    apply fholo; auto.
  - auto_cts.
    apply fholo; auto.
Qed.

Lemma Copp_mult :forall z,
  -z = -1 * z.
Proof.
  move => z.
  simplify_as_R2 LHS;
  simplify_as_R2 RHS;
  auto.
Qed.

Lemma ext_CHolo_on : forall D f g,
(forall z, f z = g z) ->
  CHolo_on D f <-> CHolo_on D g.
Proof.
  move => D f g ext.
  split;
  move => [f' H];
  exists f' => z Dz;
  split.
  - apply (is_derive_ext f); auto.
    apply H; auto.
  - apply H; auto.
  - apply (is_derive_ext g); auto.
    apply H; auto.
  - apply H; auto.
Qed.

Hint Extern 5 (continuous _ _) => (apply/cts_topology_2) : teardown_leaf.

Lemma CHolo_on_mult: forall D f g,
  CHolo_on D f ->
  CHolo_on D g ->
  CHolo_on D (fun z => f z * g z )
.
Proof.
  move => D f g [f' fholo] [g' gholo].
  exists (fun q => f' q * g q + f q * g' q) => z Dz.
  split.
  - move: fholo => /(_ z Dz) [/diff_topology_change fholo _].
    move: gholo => /(_ z Dz) [/diff_topology_change gholo _].
    rewrite /Holo /is_derive in fholo gholo.
    have:= (@filterdiff_mult_fct
      C_AbsRing
      (AbsRing_NormedModule C_AbsRing)
      f g z _ _ Cmult_comm fholo gholo ).
    move => H.
    apply/diff_topology_change.
    rewrite /is_derive.
    move: H => //=.
    unfold_alg => H.
    under ext_filterdiff_d => t.
      set p := _ * _.
      replace p with (t * f' z * g z + f z * (t * g' z)).
    over.
    rewrite /p; field_simplify_eq; auto.
    auto.
  - move: (fholo z Dz) => [/is_derive_continuous df cf'].
    move: (gholo z Dz) => [/is_derive_continuous dg cg'].
    auto_cts.
Qed.

Lemma Cmult_zero : forall z,
  z * z = 0 -> z = 0.
Proof.
  move => z H.
  apply Cmod_eq_0.
  have: (Cmod z * Cmod z = 0)%R.
  2: by nra.
  rewrite -Cmod_mult -Cmod_0.
  by f_equal.
Qed.

Lemma CHolo_on_const: forall D k,
  CHolo_on D (fun => k).
Proof.
  move => D k.
  exists (fun => 0) => z Dz.
  split.
  - apply: is_derive_const.
  - auto_cts.
Qed.

Lemma CHolo_on_id: forall D,
  CHolo_on D id.
Proof.
  move => D.
  exists (fun => one) => z Dz.
  split.
  - apply/diff_topology_change; apply: is_derive_id.
  - auto_cts.
Qed.

Lemma CHolo_on_div: forall D f,
  CHolo_on D f ->
  (forall z, D z -> f z <> 0) ->
  CHolo_on D (fun z => / (f z) )
.
Proof.
  move => D f [f' fholo].
  exists (fun q => f' q * (-1/((f q * f q)))) => z Dz.
  split.
  - move: fholo => /(_ z Dz) [/diff_topology_change fholo _].
    rewrite /Holo /is_derive in fholo.
    apply: is_derive_comp; last by apply: fholo.
    apply holo_inv; auto.
  - move: (fholo z Dz) => [/is_derive_continuous df cf'].
    have Q:= @holo_inv (f z * f z).
    auto_cts.
    apply/cts_topology_1/cts_topology_2.
    apply: is_derive_continuous.
    apply: Q.
    move => /Cmult_zero.
    apply H.
    auto.
Qed.

End CHoloTeardown.

Hint Extern 1 (CHolo_on _ id _) => (apply: CHolo_on_id) : teardown_leaf.
Hint Extern 1 (CHolo_on _ (fun =>_) _) => (apply: CHolo_on_const) : teardown_leaf.
Ltac auto_CHolo_on :=
  rewrite /Rdiv /Cdiv;
  repeat (teardown
          (fail "no topology change for CHolo")
          (apply: CHolo_on_plus)
          (unfold_alg; apply: CHolo_on_mult)
          (apply: CHolo_on_mult)
          (apply: CHolo_on_plus)
          (apply: CHolo_on_opp)
          (apply: CHolo_on_div)
          (fail "no CHolo for pairs"));
 auto with teardown_leaf.

Open Scope C.

Lemma pow_n_abs_C : forall (z:C) n, Cmod (pow_n z n)%C = (pow_n (Cmod z) n).
Proof.
  move => z.
  elim.
  - simpl. apply Cmod_1.
  - move => n IH //=.
    rewrite Cmod_mult IH //=.
Qed.

Lemma pow_n_cts : forall z n, continuous (fun z:C => pow_n z n) z.
Proof.
  move => z.
  elim.
  - simpl; auto_cts.
  - move => n IH //=.
    apply/cts_topology_1.
    apply/cts_topology_2.
    apply: continuous_mult; auto_cts.
Qed.

Lemma pow_n_neq_0: forall (z:C) n , z <> (0,0) -> pow_n z n <> (0,0).
Proof.
  move => z + H.
  elim.
  - simpl.
    rewrite /one /=.
    move => /pair_equal_spec [? _].
    lra.
  - move => n IH.
    simpl.
    rewrite /mult /=.
    apply Cmult_neq_0; auto.
Qed.

Hint Extern 5 (continuous _ _ ) =>
  (apply: ex_derive_continuous; eexists; eauto) : teardown_leaf.

Hint Extern 2 (continuous (fun _ => pow_n _ ?n) _ ) =>
  apply: (@continuous_comp _ _ _ _ (fun z:C => pow_n z n)) :teardown_leaf.

Hint Extern 2 (continuous (pow_n ^~ _) _ ) =>
  (apply: pow_n_cts): teardown_leaf.

Section Contours.
  Open Scope C.

  Definition c_circle (r: R) (t:R):C := r * (cos t, sin t).
  Definition c_circle' (r: R) (t:R):C := r * (-sin t, cos t)%R.

  Lemma c_circle_norm: forall r t,
    Cmod( (r*cos t, r * sin t))%R = Rabs r.
  Proof.
    move => r t.
    elim_norms.
    - nra.
    - field_simplify_eq.
      rewrite -Rmult_plus_distr_l Rplus_comm
              -?Rsqr_pow2 sin2_cos2.
      lra.
  Qed.

  Lemma c_circle_norm_2: forall r t,
    Cmod(c_circle r t) = Rabs r.
  Proof.
    move => r t.
    elim_norms.
    - nra.
    - field_simplify_eq.
      rewrite -Rmult_plus_distr_l Rplus_comm
              -?Rsqr_pow2 sin2_cos2.
      lra.
  Qed.

  Lemma c_circle'_norm: forall r t,
    Cmod(c_circle' r t) = Rabs r.
  Proof.
    move => r t.
    elim_norms.
    - nra.
    - field_simplify_eq.
      rewrite -Rmult_plus_distr_l
              -?Rsqr_pow2 sin2_cos2.
      lra.
  Qed.

  Record Contour := mkContour {
    gamma: R -> C;
    gamma': R -> C;
    l_end: R;
    r_end: R;
    endpoint_interval: l_end < r_end;
    contour_derive: forall t, l_end <= t <= r_end -> is_derive gamma t (gamma' t);
    cts_derive: forall t, l_end <= t <= r_end -> continuous gamma' t;
  }.

  Definition is_CInt (g: Contour) (f: C -> C) (z:C) :=
    is_RInt (fun t => f (gamma g t) * (gamma' g t)) (l_end g) (r_end g) z.

  Definition ex_CInt (g: Contour) (f: C -> C) :=
    exists z, is_CInt g f z.

  Definition CInt (g: Contour ) f :=
    RInt (V:=C_R_CompleteNormedModule)
      (fun t => f (gamma g t) * (gamma' g t)) (l_end g) (r_end g) .

  Program Definition circC (z:C) (r: R) := {|
    gamma := fun t => z + c_circle r t;
    gamma' := c_circle' r;
    l_end := 0;
    r_end := 2*PI;
  |}.
  Obligation 1.
  Proof. have:= PI_RGT_0; lra. Qed.
  Obligation 2.
  Proof.
    rewrite /c_circle /c_circle'.
    under ext_is_derive_glo => y.
      simplify_as_R2 (_ + _) .
    over.
    simplify_as_R2 (x in is_derive _ _ x).
    apply/ is_derive_pair; split; auto_derive; auto; field_simplify; auto.
  Qed.

  Obligation 3.
  Proof.
    rewrite /c_circle'.
    auto_cts.
    1,2: apply: ex_derive_continuous; auto_derive; auto.
  Qed.

  Definition cts_on_contour (f: C -> C) g :=
    forall t, l_end g <= t <= r_end g -> continuous f (gamma g t).

  Lemma cts_on_contour_mult: forall f g gam,
    cts_on_contour f gam ->
    cts_on_contour g gam ->
    cts_on_contour (fun z => f z * g z) gam.
  Proof. move => *??; auto_cts. Qed.

  Lemma cts_on_contour_plus: forall f g gam,
    cts_on_contour f gam ->
    cts_on_contour g gam ->
    cts_on_contour (fun z => f z + g z) gam.
  Proof. move => *??; auto_cts. Qed.
  Lemma cts_on_contour_minus: forall f g gam,
    cts_on_contour f gam ->
    cts_on_contour g gam ->
    cts_on_contour (fun z => f z - g z) gam.
  Proof. move => *??; auto_cts. Qed.

  Lemma cts_on_contour_opp: forall f gam,
    cts_on_contour f gam ->
    cts_on_contour (fun z => - f z) gam.
  Proof. move => *??; auto_cts. Qed.

  Lemma ex_CInt_RInt: forall f g,
    ex_RInt (fun t => f (gamma g t) * (gamma' g t)) (l_end g) (r_end g) <->
    ex_CInt g f.
  Proof.
    move => f g; split;
    move => [l H]; exists l; apply H.
  Qed.

  Lemma ReImSplit : forall z,
    (Re z, Im z) = z.
  Proof.
    move => z.
    rewrite /Re /Im /Cplus //=.
    set p := LHS.
    simplify_as_R2 LHS.
    rewrite -surjective_pairing //=.
  Qed.

  Lemma split_cint : forall (f: R -> C) a b,
    ex_RInt f a b ->
    RInt (V:=C_R_CompleteNormedModule) f a b =
    (RInt (compose Re f) a b, RInt (compose Im f) a b).
  Proof.
    move => f a b [l isR].
    rewrite /Re /Im /compose.
    apply: is_RInt_unique.
    apply: is_RInt_fct_extend_pair.
    - move: isR.
      copy => /is_RInt_fct_extend_fst /is_RInt_unique ->.
      apply is_RInt_fct_extend_fst.
    - move: isR.
      copy => /is_RInt_fct_extend_snd /is_RInt_unique ->.
      apply is_RInt_fct_extend_snd.
  Qed.
    Lemma cts_CInt: forall (f: C -> C) g,
    cts_on_contour f g -> ex_CInt g f.
  Proof.
    move => f g cts.
    rewrite -ex_CInt_RInt -ex_RInt_prod.
    apply: ex_RInt_continuous => t tbd.
    rewrite Rmin_left in tbd.
    rewrite Rmax_right in tbd.
    2-3: left; apply endpoint_interval.
    have ?:= @cts_derive g t (ltac:(auto)).
    have := @contour_derive g t (ltac:(auto)).
    move => /is_derive_continuous ?.
    move:cts => /(_ t (ltac:(auto))) ?.
    auto_cts.
    apply: continuous_comp;
    auto_cts.
  Qed.
  Lemma CInt_ext : forall f g gam,
    (forall t, l_end gam <= t <= r_end gam -> f (gamma gam t) = g (gamma gam t)) ->
    CInt (gam) f = CInt (gam) g.
  Proof.
    move => f g gam ext.
    rewrite /CInt.
    under RInt_ext => t tbd.
     rewrite ext.
    over.
    2: auto.
    rewrite Rmin_left in tbd.
    rewrite Rmax_right in tbd.
    lra.
    all: left; apply endpoint_interval.
  Qed.

  Lemma CInt_ext_global : forall f g gam,
    (forall z,  f z = g z) ->
    CInt (gam) f = CInt (gam) g.
  Proof.
    move => f g gam ext.
    under CInt_ext => t _ do rewrite ext.
    auto.
  Qed.

  Lemma CInt_plus : forall f g gam,
    cts_on_contour g gam ->
    cts_on_contour f gam ->
    CInt (gam) (fun z => f z + g z) =
    CInt (gam) f + CInt ( gam) g.
  Proof.
    move => f g ctsf ctsg gam.
    rewrite /CInt.
    under RInt_ext => t _ do rewrite Cmult_plus_distr_r.
    rewrite RInt_plus; first by [];
    apply ex_CInt_RInt, cts_CInt; auto.
  Qed.

  Lemma CInt_mult_Ci : forall f gam,
    cts_on_contour f gam ->
    CInt (gam) (fun z => Ci * f z) =
    Ci * CInt (gam) f .
  Proof.
    move => f gam ctsf.
    rewrite /CInt split_cint /compose //=.
    under RInt_ext => t tbd do field_simplify.
    under [x in (_,x)]RInt_ext => t tbd do field_simplify.

    rewrite split_cint.
    simplify_as_R2 RHS.
    symmetry.
    rewrite /compose.
    simpl.
    f_equal.
    set p := (x in Ropp x).
    replace (-p)%R with (opp p); last by unfold_alg.
    rewrite /p.
    rewrite -RInt_opp.
    under RInt_ext => t _.
      unfold_alg.
      field_simplify.
    over.
    auto.
    - apply ex_RInt_continuous => t tbd.
      rewrite Rmin_left in tbd; last (by left; apply endpoint_interval);
      rewrite Rmax_right in tbd; last (by left; apply endpoint_interval).
      auto_cts; apply continuous_comp; auto_cts.
      2,4: apply: cts_derive; auto.
      all: apply continuous_comp; auto_cts.
      all: apply: ex_derive_continuous; eexists; apply contour_derive; auto.
    - apply/ ex_CInt_RInt.
      apply: cts_CInt .
      auto.
    - apply (@ex_CInt_RInt (fun z => Ci * f z)).
      apply: cts_CInt .
      apply cts_on_contour_mult; last by auto.
      move => *. apply continuous_const.
  Qed.

  Lemma ReImSplit_plus : forall z,
    z = Re z + Ci * Im z.
  Proof.
    move => z.
    rewrite /Re /Ci/Im /Cmult.
    simpl.
    simplify_as_R2 RHS.
    rewrite -surjective_pairing.
    auto.
  Qed.

  Lemma CInt_mult : forall f k gam,
    cts_on_contour f gam ->
    CInt (gam) (fun z => k * f z) =
    k * CInt (gam) f .
  Proof.
    move => f k gam cstf.
    rewrite (@ReImSplit_plus k).
    under CInt_ext_global => t do
      rewrite Cmult_plus_distr_r .
    rewrite CInt_plus.
    2-3 : by
      apply: cts_on_contour_mult; last by [];
      move => *; apply: continuous_const.
    rewrite {1}/CInt.
    under RInt_ext => t _ do
      rewrite -Cmult_assoc -scal_R_Cmult.
    rewrite RInt_scal; last by
      apply/ ex_CInt_RInt;
      apply: cts_CInt .
    rewrite scal_R_Cmult.
    rewrite [RHS]Cmult_plus_distr_r.
    rewrite -/(CInt _).
    f_equal.
    rewrite {1}/CInt.
    under RInt_ext => t _.
      set p := _ * _ * _ * _.
      replace p with (Im k * (Ci * f (gamma gam t) * gamma' gam t )); last by
        rewrite /p; field_simplify.
      rewrite -scal_R_Cmult.
    over.
    rewrite RInt_scal.
    - rewrite scal_R_Cmult.
      rewrite -/(CInt _ (fun z => Ci * f z)).
      rewrite CInt_mult_Ci; last by [].
      field_simplify.
      auto.
    - apply (@ex_CInt_RInt (fun z => Ci * f z)).
      apply cts_CInt .
      apply cts_on_contour_mult; last by [].
      move => *. apply continuous_const.
  Qed.

  Lemma div_continuous_circle: forall a (r: posreal) ,
    cts_on_contour (fun q : C => Cinv (q - a)) (circC a r).
  Proof.
    move => a r t tbd; simpl in *.
    have ?:= cond_pos r.
    auto_cts.
    simple apply continuous_Cinv.
    simplify_as_R2 (x in x <> _).
    rewrite Cmod_gt_0 c_circle_norm Rabs_pos_eq; nra.
  Qed.
  Lemma div_pow_continuous_circle: forall a (r: posreal) n ,
    cts_on_contour (fun q : C => Cinv (pow_n (q - a) n)) (circC a r).
  Proof.
    move => a r n t tbd; simpl in *.
    have ?:= cond_pos r.
    auto_cts.
    1: apply: (@continuous_comp _ _ _ _ (fun z:C => pow_n z n)); auto_cts.
    apply: continuous_Cinv.
    apply: pow_n_neq_0.
    simplify_as_R2 (x in x <> _).
    rewrite Cmod_gt_0 c_circle_norm Rabs_pos_eq; nra.
  Qed.

End Contours.

Ltac auto_cts_on_contour :=
  repeat (teardown
    (fail "no topology stuff here")
    (apply: cts_on_contour_plus)
    (unfold_alg; apply: cts_on_contour_mult)
    (apply: cts_on_contour_mult)
    (apply: cts_on_contour_minus)
    (apply: cts_on_contour_opp)
    (try (apply: div_continuous_circle);
     try (apply: div_pow_continuous_circle))
    (fail "no cts_on_contour for pairs"));
 auto with teardown_leaf.


(** * StlcProp: Properties of STLC *)

Set Warnings "-notation-overridden,-parsing".
From PLF Require Import Maps.
From PLF Require Import Types.
From PLF Require Import Stlc.
From PLF Require Import Smallstep.
Module STLCProp.
Import STLC.

(** In this chapter, we develop the fundamental theory of the Simply
    Typed Lambda Calculus -- in particular, the type safety
    theorem. *)

(* ################################################################# *)
(** * Canonical Forms *)

(** As we saw for the simple calculus in the [Types] chapter, the
    first step in establishing basic properties of reduction and types
    is to identify the possible _canonical forms_ (i.e., well-typed
    closed values) belonging to each type.  For [Bool], these are the
    boolean values [ttrue] and [tfalse]; for arrow types, they are
    lambda-abstractions.  *)

Lemma canonical_forms_bool : forall t,
  empty |- t \in TBool ->
  value t ->
  (t = ttrue) \/ (t = tfalse).
Proof.
  intros t HT HVal.
  inversion HVal; intros; subst; try inversion HT; auto.
Qed.

Lemma canonical_forms_fun : forall t T1 T2,
  empty |- t \in (TArrow T1 T2) ->
  value t ->
  exists x u, t = tabs x T1 u.
Proof.
  intros t T1 T2 HT HVal.
  inversion HVal; intros; subst; try inversion HT; subst; auto.
  exists x0. exists t0.  auto.
Qed.

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

(** The _progress_ theorem tells us that closed, well-typed
    terms are not stuck: either a well-typed term is a value, or it
    can take a reduction step.  The proof is a relatively
    straightforward extension of the progress proof we saw in the
    [Types] chapter.  We'll give the proof in English first, then
    the formal version. *)

Theorem progress : forall t T,
  empty |- t \in T ->
  value t \/ exists t', t ==> t'.

(** _Proof_: By induction on the derivation of [|- t \in T].

    - The last rule of the derivation cannot be [T_Var], since a
      variable is never well typed in an empty context.

    - The [T_True], [T_False], and [T_Abs] cases are trivial, since in
      each of these cases we can see by inspecting the rule that [t]
      is a value.

    - If the last rule of the derivation is [T_App], then [t] has the
      form [t1 t2] for some [t1] and [t2], where [|- t1 \in T2 -> T]
      and [|- t2 \in T2] for some type [T2].  By the induction
      hypothesis, either [t1] is a value or it can take a reduction
      step.

        - If [t1] is a value, then consider [t2], which by the other
          induction hypothesis must also either be a value or take a
          step.

            - Suppose [t2] is a value.  Since [t1] is a value with an
              arrow type, it must be a lambda abstraction; hence [t1
              t2] can take a step by [ST_AppAbs].

            - Otherwise, [t2] can take a step, and hence so can [t1
              t2] by [ST_App2].

        - If [t1] can take a step, then so can [t1 t2] by [ST_App1].

    - If the last rule of the derivation is [T_If], then [t = if t1
      then t2 else t3], where [t1] has type [Bool].  By the IH, [t1]
      either is a value or takes a step.

        - If [t1] is a value, then since it has type [Bool] it must be
          either [true] or [false].  If it is [true], then [t] steps
          to [t2]; otherwise it steps to [t3].

        - Otherwise, [t1] takes a step, and therefore so does [t] (by
          [ST_If]). *)
Proof with eauto.
  intros t T Ht.
  remember (@empty ty) as Gamma.
  induction Ht; subst Gamma...
  - (* T_Var *)
    (* contradictory: variables cannot be typed in an
       empty context *)
    inversion H.

  - (* T_App *)
    (* [t] = [t1 t2].  Proceed by cases on whether [t1] is a
       value or steps... *)
    right. destruct IHHt1...
    + (* t1 is a value *)
      destruct IHHt2...
      * (* t2 is also a value *)
        assert (exists x0 t0, t1 = tabs x0 T11 t0).
        eapply canonical_forms_fun; eauto.
        destruct H1 as [x0 [t0 Heq]]. subst.
        exists ([x0:=t2]t0)...

      * (* t2 steps *)
        inversion H0 as [t2' Hstp]. exists (tapp t1 t2')...

    + (* t1 steps *)
      inversion H as [t1' Hstp]. exists (tapp t1' t2)...

  - (* T_If *)
    right. destruct IHHt1...

    + (* t1 is a value *)
      destruct (canonical_forms_bool t1); subst; eauto.

    + (* t1 also steps *)
      inversion H as [t1' Hstp]. exists (tif t1' t2 t3)...
Qed.

(** **** Exercise: 3 stars, advanced (progress_from_term_ind)  *)
(** Show that progress can also be proved by induction on terms
    instead of induction on typing derivations. *)

Theorem progress' : forall t T,
     empty |- t \in T ->
     value t \/ exists t', t ==> t'.
Proof.
  intros t.
  induction t; intros T Ht; auto.

  - inversion Ht. inversion H1.
  -
    inversion Ht; subst.
    destruct (IHt1 _ H2); destruct (IHt2 _ H4); right.
    + assert (exists x0 t0, t1 = tabs x0 T11 t0).
        eapply canonical_forms_fun; eauto.
      destruct H1 as [x0 [t0 HH]].
      exists ([x0:=t2]t0). subst. auto.
    + destruct H0. eauto.
    + destruct H. eauto.
    + destruct H. eauto.
  - inversion Ht; subst.
    destruct (IHt1 _ H3).
    destruct (canonical_forms_bool t1); subst; eauto.
    destruct H. eauto.
Qed.

(** [] *)

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

(** The other half of the type soundness property is the
    preservation of types during reduction.  For this part, we'll need
    to develop some technical machinery for reasoning about variables
    and substitution.  Working from top to bottom (from the high-level
    property we are actually interested in to the lowest-level
    technical lemmas that are needed by various cases of the more
    interesting proofs), the story goes like this:

      - The _preservation theorem_ is proved by induction on a typing
        derivation, pretty much as we did in the [Types] chapter.
        The one case that is significantly different is the one for
        the [ST_AppAbs] rule, whose definition uses the substitution
        operation.  To see that this step preserves typing, we need to
        know that the substitution itself does.  So we prove a...

      - _substitution lemma_, stating that substituting a (closed)
        term [s] for a variable [x] in a term [t] preserves the type
        of [t].  The proof goes by induction on the form of [t] and
        requires looking at all the different cases in the definition
        of substitition.  This time, the tricky cases are the ones for
        variables and for function abstractions.  In both, we discover
        that we need to take a term [s] that has been shown to be
        well-typed in some context [Gamma] and consider the same term
        [s] in a slightly different context [Gamma'].  For this we
        prove a...

      - _context invariance_ lemma, showing that typing is preserved
        under "inessential changes" to the context [Gamma] -- in
        particular, changes that do not affect any of the free
        variables of the term.  And finally, for this, we need a
        careful definition of...

      - the _free variables_ in a term -- i.e., variables that are
        used in the term and where these uses are _not_ in the scope of
        an enclosing function abstraction binding a variable of the
        same name.

   To make Coq happy, we need to formalize the story in the opposite
   order... *)

(* ================================================================= *)
(** ** Free Occurrences *)

(** A variable [x] _appears free in_ a term _t_ if [t] contains some
    occurrence of [x] that is not under an abstraction labeled [x].
    For example:
      - [y] appears free, but [x] does not, in [\x:T->U. x y]
      - both [x] and [y] appear free in [(\x:T->U. x y) x]
      - no variables appear free in [\x:T->U. \y:T. x y]

    Formally: *)

Inductive appears_free_in : string -> tm -> Prop :=
  | afi_var : forall x,
      appears_free_in x (tvar x)
  | afi_app1 : forall x t1 t2,
      appears_free_in x t1 ->
      appears_free_in x (tapp t1 t2)
  | afi_app2 : forall x t1 t2,
      appears_free_in x t2 ->
      appears_free_in x (tapp t1 t2)
  | afi_abs : forall x y T11 t12,
      y <> x  ->
      appears_free_in x t12 ->
      appears_free_in x (tabs y T11 t12)
  | afi_if1 : forall x t1 t2 t3,
      appears_free_in x t1 ->
      appears_free_in x (tif t1 t2 t3)
  | afi_if2 : forall x t1 t2 t3,
      appears_free_in x t2 ->
      appears_free_in x (tif t1 t2 t3)
  | afi_if3 : forall x t1 t2 t3,
      appears_free_in x t3 ->
      appears_free_in x (tif t1 t2 t3).

Hint Constructors appears_free_in.

(** The _free variables_ of a term are just the variables that appear
    free in it.  A term with no free variables is said to be
    _closed_. *)

Definition closed (t:tm) :=
  forall x, ~ appears_free_in x t.

(** An _open_ term is one that may contain free variables.  (I.e., every
    term is an open term; the closed terms are a subset of the open ones.
    "Open" really means "possibly containing free variables.") *)

(** **** Exercise: 1 star (afi)  *)
(** In the space below, write out the rules of the [appears_free_in]
    relation in informal inference-rule notation.  (Use whatever
    notational conventions you like -- the point of the exercise is
    just for you to think a bit about the meaning of each rule.)
    Although this is a rather low-level, technical definition,
    understanding it is crucial to understanding substitution and its
    properties, which are really the crux of the lambda-calculus. *)

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_afi : option (prod nat string) := None.
(** [] *)

(* ================================================================= *)
(** ** Substitution *)

(** To prove that substitution preserves typing, we first need a
    technical lemma connecting free variables and typing contexts: If
    a variable [x] appears free in a term [t], and if we know [t] is
    well typed in context [Gamma], then it must be the case that
    [Gamma] assigns a type to [x]. *)

Lemma free_in_context : forall x t T Gamma,
   appears_free_in x t ->
   Gamma |- t \in T ->
   exists T', Gamma x = Some T'.

(** _Proof_: We show, by induction on the proof that [x] appears free
      in [t], that, for all contexts [Gamma], if [t] is well typed
      under [Gamma], then [Gamma] assigns some type to [x].

      - If the last rule used is [afi_var], then [t = x], and from the
        assumption that [t] is well typed under [Gamma] we have
        immediately that [Gamma] assigns a type to [x].

      - If the last rule used is [afi_app1], then [t = t1 t2] and [x]
        appears free in [t1].  Since [t] is well typed under [Gamma],
        we can see from the typing rules that [t1] must also be, and
        the IH then tells us that [Gamma] assigns [x] a type.

      - Almost all the other cases are similar: [x] appears free in a
        subterm of [t], and since [t] is well typed under [Gamma], we
        know the subterm of [t] in which [x] appears is well typed
        under [Gamma] as well, and the IH gives us exactly the
        conclusion we want.

      - The only remaining case is [afi_abs].  In this case [t =
        \y:T11.t12] and [x] appears free in [t12], and we also know
        that [x] is different from [y].  The difference from the
        previous cases is that, whereas [t] is well typed under
        [Gamma], its body [t12] is well typed under [(Gamma & {{y-->T11}}],
        so the IH allows us to conclude that [x] is assigned some type
        by the extended context [(Gamma & {{y-->T11}}].  To conclude that
        [Gamma] assigns a type to [x], we appeal to lemma
        [update_neq], noting that [x] and [y] are different
        variables. *)

Proof.
  intros x t T Gamma H H0. generalize dependent Gamma.
  generalize dependent T.
  induction H;
         intros; try solve [inversion H0; eauto].
  - (* afi_abs *)
    inversion H1; subst.
    apply IHappears_free_in in H7.
    rewrite update_neq in H7; assumption.
Qed.

(** Next, we'll need the fact that any term [t] that is well typed in
    the empty context is closed (it has no free variables). *)

(** **** Exercise: 2 stars, optional (typable_empty__closed)  *)
Corollary typable_empty__closed : forall t T,
    empty |- t \in T  ->
    closed t.
Proof. unfold closed. intros.
  intro contra.
  assert (exists T', (@empty ty) x0 = Some T').
  eapply free_in_context; eauto.
  inversion H0. inversion H1.
Qed.

(** [] *)

(** Sometimes, when we have a proof [Gamma |- t : T], we will need to
    replace [Gamma] by a different context [Gamma'].  When is it safe
    to do this?  Intuitively, it must at least be the case that
    [Gamma'] assigns the same types as [Gamma] to all the variables
    that appear free in [t]. In fact, this is the only condition that
    is needed. *)

Lemma context_invariance : forall Gamma Gamma' t T,
     Gamma |- t \in T  ->
     (forall x, appears_free_in x t -> Gamma x = Gamma' x) ->
     Gamma' |- t \in T.

(** _Proof_: By induction on the derivation of [Gamma |- t \in T].

      - If the last rule in the derivation was [T_Var], then [t = x]
        and [Gamma x = T].  By assumption, [Gamma' x = T] as well, and
        hence [Gamma' |- t \in T] by [T_Var].

      - If the last rule was [T_Abs], then [t = \y:T11. t12], with [T
        = T11 -> T12] and [Gamma & {{y-->T11}} |- t12 \in T12].  The
        induction hypothesis is that, for any context [Gamma''], if
        [Gamma & {{y-->T11}}] and [Gamma''] assign the same types to
        all the free variables in [t12], then [t12] has type [T12]
        under [Gamma''].  Let [Gamma'] be a context which agrees with
        [Gamma] on the free variables in [t]; we must show [Gamma' |-
        \y:T11. t12 \in T11 -> T12].

        By [T_Abs], it suffices to show that [Gamma' & {{y-->T11}} |-
        t12 \in T12].  By the IH (setting [Gamma'' = Gamma' &
        {{y:T11}}]), it suffices to show that [Gamma & {{y-->T11}}]
        and [Gamma' & {{y-->T11}}] agree on all the variables that
        appear free in [t12].

        Any variable occurring free in [t12] must be either [y] or
        some other variable.  [Gamma & {{y-->T11}}] and [Gamma' &
        {{y-->T11}}] clearly agree on [y].  Otherwise, note that any
        variable other than [y] that occurs free in [t12] also occurs
        free in [t = \y:T11. t12], and by assumption [Gamma] and
        [Gamma'] agree on all such variables; hence so do [Gamma &
        {{y-->T11}}] and [Gamma' & {{y-->T11}}].

      - If the last rule was [T_App], then [t = t1 t2], with [Gamma |-
        t1 \in T2 -> T] and [Gamma |- t2 \in T2].  One induction
        hypothesis states that for all contexts [Gamma'], if [Gamma']
        agrees with [Gamma] on the free variables in [t1], then [t1]
        has type [T2 -> T] under [Gamma']; there is a similar IH for
        [t2].  We must show that [t1 t2] also has type [T] under
        [Gamma'], given the assumption that [Gamma'] agrees with
        [Gamma] on all the free variables in [t1 t2].  By [T_App], it
        suffices to show that [t1] and [t2] each have the same type
        under [Gamma'] as under [Gamma].  But all free variables in
        [t1] are also free in [t1 t2], and similarly for [t2]; hence
        the desired result follows from the induction hypotheses. *)

Proof with eauto.
  intros.
  generalize dependent Gamma'.
  induction H; intros; auto.
  - (* T_Var *)
    apply T_Var. rewrite <- H0...
  - (* T_Abs *)
    apply T_Abs.
    apply IHhas_type. intros x1 Hafi.
    (* the only tricky step... the [Gamma'] we use to
       instantiate is [Gamma & {{x-->T11}}] *)
    unfold update. unfold t_update. destruct (beq_string x0 x1) eqn: Hx0x1...
    rewrite beq_string_false_iff in Hx0x1. auto.
  - (* T_App *)
    apply T_App with T11...
Qed.

(** Now we come to the conceptual heart of the proof that reduction
    preserves types -- namely, the observation that _substitution_
    preserves types. *)

(** Formally, the so-called _substitution lemma_ says this:
    Suppose we have a term [t] with a free variable [x], and suppose
    we've assigned a type [T] to [t] under the assumption that [x] has
    some type [U].  Also, suppose that we have some other term [v] and
    that we've shown that [v] has type [U].  Then, since [v] satisfies
    the assumption we made about [x] when typing [t], we can
    substitute [v] for each of the occurrences of [x] in [t] and
    obtain a new term that still has type [T]. *)

(** _Lemma_: If [Gamma & {{x-->U}} |- t \in T] and [|- v \in U],
    then [Gamma |- [x:=v]t \in T]. *)

Lemma substitution_preserves_typing : forall Gamma x U t v T,
  Gamma & {{x-->U}} |- t \in T ->
  empty |- v \in U   ->
  Gamma |- [x:=v]t \in T.

(** One technical subtlety in the statement of the lemma is that
    we assume [v] has type [U] in the _empty_ context -- in other
    words, we assume [v] is closed.  This assumption considerably
    simplifies the [T_Abs] case of the proof (compared to assuming
    [Gamma |- v \in U], which would be the other reasonable assumption
    at this point) because the context invariance lemma then tells us
    that [v] has type [U] in any context at all -- we don't have to
    worry about free variables in [v] clashing with the variable being
    introduced into the context by [T_Abs].

    The substitution lemma can be viewed as a kind of commutation
    property.  Intuitively, it says that substitution and typing can
    be done in either order: we can either assign types to the terms
    [t] and [v] separately (under suitable contexts) and then combine
    them using substitution, or we can substitute first and then
    assign a type to [ [x:=v] t ] -- the result is the same either
    way.

    _Proof_: We show, by induction on [t], that for all [T] and
    [Gamma], if [Gamma & {{x-->U}} |- t \in T] and [|- v \in U], then
    [Gamma |- [x:=v]t \in T].

      - If [t] is a variable there are two cases to consider,
        depending on whether [t] is [x] or some other variable.

          - If [t = x], then from the fact that [Gamma & {{x-->U}} |-
            x \in T] we conclude that [U = T].  We must show that
            [[x:=v]x = v] has type [T] under [Gamma], given the
            assumption that [v] has type [U = T] under the empty
            context.  This follows from context invariance: if a
            closed term has type [T] in the empty context, it has that
            type in any context.

          - If [t] is some variable [y] that is not equal to [x], then
            we need only note that [y] has the same type under [Gamma
            & {{x-->U}}] as under [Gamma].

      - If [t] is an abstraction [\y:T11. t12], then the IH tells us,
        for all [Gamma'] and [T'], that if [Gamma' & {{x-->U} |- t12
        \in T'] and [|- v \in U], then [Gamma' |- [x:=v]t12 \in T'].

        The substitution in the conclusion behaves differently
        depending on whether [x] and [y] are the same variable.

        First, suppose [x = y].  Then, by the definition of
        substitution, [[x:=v]t = t], so we just need to show [Gamma |-
        t \in T].  But we know [Gamma & {{x-->U}} |- t : T], and,
        since [y] does not appear free in [\y:T11. t12], the context
        invariance lemma yields [Gamma |- t \in T].

        Second, suppose [x <> y].  We know [Gamma & {{x-->U; y-->T11}}
        |- t12 \in T12] by inversion of the typing relation, from
        which [Gamma & {{y-->T11; x-->U}} |- t12 \in T12] follows by
        the context invariance lemma, so the IH applies, giving us
        [Gamma & {{y-->T11}} |- [x:=v]t12 \in T12].  By [T_Abs],
        [Gamma |- \y:T11. [x:=v]t12 \in T11->T12], and by the
        definition of substitution (noting that [x <> y]), [Gamma |-
        \y:T11. [x:=v]t12 \in T11->T12] as required.

      - If [t] is an application [t1 t2], the result follows
        straightforwardly from the definition of substitution and the
        induction hypotheses.

      - The remaining cases are similar to the application case.

    _Technical note_: This proof is a rare case where an induction on
    terms, rather than typing derivations, yields a simpler argument.
    The reason for this is that the assumption [Gamma & {{x-->U}} |- t
    \in T] is not completely generic, in the sense that one of the
    "slots" in the typing relation -- namely the context -- is not
    just a variable, and this means that Coq's native induction tactic
    does not give us the induction hypothesis that we want.  It is
    possible to work around this, but the needed generalization is a
    little tricky.  The term [t], on the other hand, is completely
    generic. *)

Proof with eauto.
  intros Gamma x U t v T Ht Ht'.
  generalize dependent Gamma. generalize dependent T.
  induction t; intros T Gamma H;
    (* in each case, we'll want to get at the derivation of H *)
    inversion H; subst; simpl...
  - (* tvar *)
    rename s into y. destruct (beq_stringP x y) as [Hxy|Hxy].
    + (* x=y *)
      subst.
      rewrite update_eq in H2.
      inversion H2; subst.
      eapply context_invariance. eassumption.
      apply typable_empty__closed in Ht'. unfold closed in Ht'.
      intros.  apply (Ht' x0) in H0. inversion H0.
    + (* x<>y *)
      apply T_Var. rewrite update_neq in H2...
  - (* tabs *)
    rename s into y. rename t into T. apply T_Abs.
    destruct (beq_stringP x y) as [Hxy | Hxy].
    + (* x=y *)
      subst. rewrite update_shadow in H5. apply H5.
    + (* x<>y *)
      apply IHt. Search update.
      rewrite update_permute; auto.
Qed.

(* ================================================================= *)
(** ** Main Theorem *)

(** We now have the tools we need to prove preservation: if a closed
    term [t] has type [T] and takes a step to [t'], then [t']
    is also a closed term with type [T].  In other words, the small-step
    reduction relation preserves types. *)

Theorem preservation : forall t t' T,
  empty |- t \in T  ->
  t ==> t'  ->
  empty |- t' \in T.

(** _Proof_: By induction on the derivation of [|- t \in T].

    - We can immediately rule out [T_Var], [T_Abs], [T_True], and
      [T_False] as the final rules in the derivation, since in each of
      these cases [t] cannot take a step.

    - If the last rule in the derivation is [T_App], then [t = t1
      t2].  There are three cases to consider, one for each rule that
      could be used to show that [t1 t2] takes a step to [t'].

        - If [t1 t2] takes a step by [ST_App1], with [t1] stepping to
          [t1'], then by the IH [t1'] has the same type as [t1], and
          hence [t1' t2] has the same type as [t1 t2].

        - The [ST_App2] case is similar.

        - If [t1 t2] takes a step by [ST_AppAbs], then [t1 =
          \x:T11.t12] and [t1 t2] steps to [[x:=t2]t12]; the
          desired result now follows from the fact that substitution
          preserves types.

    - If the last rule in the derivation is [T_If], then [t = if t1
      then t2 else t3], and there are again three cases depending on
      how [t] steps.

        - If [t] steps to [t2] or [t3], the result is immediate, since
          [t2] and [t3] have the same type as [t].

        - Otherwise, [t] steps by [ST_If], and the desired conclusion
          follows directly from the induction hypothesis. *)

Proof with eauto.
  remember (@empty ty) as Gamma.
  intros t t' T HT. generalize dependent t'.
  induction HT;
       intros t' HE; subst Gamma; subst;
       try solve [inversion HE; subst; auto].
  - (* T_App *)
    inversion HE; subst...
    (* Most of the cases are immediate by induction,
       and [eauto] takes care of them *)
    + (* ST_AppAbs *)
      apply substitution_preserves_typing with T11...
      inversion HT1...
Qed.

(** **** Exercise: 2 stars, recommended (subject_expansion_stlc)  *)
(** An exercise in the [Types] chapter asked about the _subject
    expansion_ property for the simple language of arithmetic and
    boolean expressions.  Does this property hold for STLC?  That is,
    is it always the case that, if [t ==> t'] and [has_type t' T],
    then [empty |- t \in T]?  If so, prove it.  If not, give a
    counter-example not involving conditionals.

    You can state your counterexample informally
    in words, with a brief explanation.

(* FILL IN HERE *)
*)

(* Do not modify the following line: *)
Definition manual_grade_for_subject_expansion_stlc : option (prod nat string) := None.
(** [] *)

(* ################################################################# *)
(** * Type Soundness *)

(** **** Exercise: 2 stars, optional (type_soundness)  *)
(** Put progress and preservation together and show that a well-typed
    term can _never_ reach a stuck state.  *)

Definition stuck (t:tm) : Prop :=
  (normal_form step) t /\ ~ value t.

Corollary soundness : forall t t' T,
  empty |- t \in T ->
  t ==>* t' ->
  ~(stuck t').
Proof.
  intros t t' T Hhas_type Hmulti. unfold stuck.
  intros [Hnf Hnot_val]. unfold normal_form in Hnf.
  induction Hmulti.
  - apply progress in Hhas_type. destruct Hhas_type; auto.
  - apply (preservation x0 y0) in Hhas_type; auto.
Qed.

(** [] *)

(* ################################################################# *)
(** * Uniqueness of Types *)

(** **** Exercise: 3 stars (types_unique)  *)
(** Another nice property of the STLC is that types are unique: a
    given term (in a given context) has at most one type. *)
(** Formalize this statement as a theorem called
      [unique_types], and prove your theorem. *)

Corollary unique_types : forall t Gamma T T',
  Gamma |- t \in T ->
  Gamma |- t \in T' ->
  T = T'.
Proof. induction t; intros;
  inversion H; inversion H0; subst; try auto.

  rewrite H3 in H7. inversion H7. auto.

  pose (IHt1 _ _ _ H4 H10).
  inversion e; auto.

  pose (IHt _ _ _ H6 H12).
  inversion e; auto.

  pose (IHt2 _ _ _ H7 H15).
  inversion e; auto.
Qed.

(* Do not modify the following line: *)
Definition manual_grade_for_types_unique : option (prod nat string) := None.
(** [] *)

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

(** **** Exercise: 1 star (progress_preservation_statement)  *)
(** Without peeking at their statements above, write down the progress
    and preservation theorems for the simply typed lambda-calculus (as
    Coq theorems).
    You can write [Admitted] for the proofs. *)
(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_progress_preservation_statement : option (prod nat string) := None.
(** [] *)

(** **** Exercise: 2 stars (stlc_variation1)  *)
(** Suppose we add a new term [zap] with the following reduction rule

                         ---------                  (ST_Zap)
                         t ==> zap

and the following typing rule:

                      ----------------               (T_Zap)
                      Gamma |- zap : T

    Which of the following properties of the STLC remain true in
    the presence of these rules?  For each property, write either
    "remains true" or "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)

(* Do not modify the following line: *)
Definition manual_grade_for_stlc_variation1 : option (prod nat string) := None.
(** [] *)

(** **** Exercise: 2 stars (stlc_variation2)  *)
(** Suppose instead that we add a new term [foo] with the following
    reduction rules:

                       -----------------                (ST_Foo1)
                       (\x:A. x) ==> foo

                         ------------                   (ST_Foo2)
                         foo ==> true

    Which of the following properties of the STLC remain true in
    the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)

(* Do not modify the following line: *)
Definition manual_grade_for_stlc_variation2 : option (prod nat string) := None.
(** [] *)

(** **** Exercise: 2 stars (stlc_variation3)  *)
(** Suppose instead that we remove the rule [ST_App1] from the [step]
    relation. Which of the following properties of the STLC remain
    true in the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)

(* Do not modify the following line: *)
Definition manual_grade_for_stlc_variation3 : option (prod nat string) := None.
(** [] *)

(** **** Exercise: 2 stars, optional (stlc_variation4)  *)
(** Suppose instead that we add the following new rule to the
    reduction relation:

            ----------------------------------        (ST_FunnyIfTrue)
            (if true then t1 else t2) ==> true

    Which of the following properties of the STLC remain true in
    the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)
(** [] *)

(** **** Exercise: 2 stars, optional (stlc_variation5)  *)
(** Suppose instead that we add the following new rule to the typing
    relation:

                 Gamma |- t1 \in Bool->Bool->Bool
                     Gamma |- t2 \in Bool
                 ------------------------------          (T_FunnyApp)
                    Gamma |- t1 t2 \in Bool

    Which of the following properties of the STLC remain true in
    the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)
(** [] *)

(** **** Exercise: 2 stars, optional (stlc_variation6)  *)
(** Suppose instead that we add the following new rule to the typing
    relation:

                     Gamma |- t1 \in Bool
                     Gamma |- t2 \in Bool
                    ---------------------               (T_FunnyApp')
                    Gamma |- t1 t2 \in Bool

    Which of the following properties of the STLC remain true in
    the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)
(** [] *)

(** **** Exercise: 2 stars, optional (stlc_variation7)  *)
(** Suppose we add the following new rule to the typing relation
    of the STLC:

                         ------------------- (T_FunnyAbs)
                         |- \x:Bool.t \in Bool

    Which of the following properties of the STLC remain true in
    the presence of this rule?  For each one, write either
    "remains true" or else "becomes false." If a property becomes
    false, give a counterexample.

      - Determinism of [step]
(* FILL IN HERE *)
      - Progress
(* FILL IN HERE *)
      - Preservation
(* FILL IN HERE *)
*)
(** [] *)

End STLCProp.

(* ================================================================= *)
(** ** Exercise: STLC with Arithmetic *)

(** To see how the STLC might function as the core of a real
    programming language, let's extend it with a concrete base
    type of numbers and some constants and primitive
    operators. *)

Module STLCArith.
Import STLC.

(** To types, we add a base type of natural numbers (and remove
    booleans, for brevity). *)

Inductive ty : Type :=
  | TArrow : ty -> ty -> ty
  | TNat   : ty.

(** To terms, we add natural number constants, along with
    successor, predecessor, multiplication, and zero-testing. *)

Inductive tm : Type :=
  | tvar : string -> tm
  | tapp : tm -> tm -> tm
  | tabs : string -> ty -> tm -> tm
  | tnat  : nat -> tm
  | tsucc : tm -> tm
  | tpred : tm -> tm
  | tmult : tm -> tm -> tm
  | tif0  : tm -> tm -> tm -> tm.

(** **** Exercise: 4 stars (stlc_arith)  *)
(** Finish formalizing the definition and properties of the STLC
    extended with arithmetic. This is a longer exercise. Specifically:

    1. Copy the core definitions for STLC that we went through,
        as well as the key lemmas and theorems, and paste them
        into the file at this point. Do not copy examples, exercises,
        etc. (In particular, make sure you don't copy any of the []
        comments at the end of exercises, to avoid confusing the
        autograder.)

        You should copy over five definitions:
          - Fixpoint susbt
          - Inductive value
          - Inductive step
          - Inductive has_type
          - Inductive appears_free_in

        And five theorems, with their proofs:
          - Lemma context_invariance
          - Lemma free_in_context
          - Lemma substitution_preserves_typing
          - Theorem preservation
          - Theorem progress

        It will be helpful to also copy over "Reserved Notation",
        "Notation", and "Hint Constructors" for these things.

    2. Edit and extend the five definitions (subst, value, step,
        has_type, and appears_free_in) so they are appropriate
        for the new STLC extended with arithmetic.

    3. Extend the proofs of all the five properties of the original
        STLC to deal with the new syntactic forms. Make sure Coq
        accepts the whole file. *)

(* FILL IN HERE *)

(* Do not modify the following line: *)
Definition manual_grade_for_stlc_arith : option (prod nat string) := None.
(** [] *)

End STLCArith.

(** $Date$ *)