/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir
-/
import algebra.geom_sum
import data.complex.basic
import data.nat.choose.sum

/-!
# Exponential, trigonometric and hyperbolic trigonometric functions

This file contains the definitions of the real and complex exponential, sine, cosine, tangent,
hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions.

-/

local notation `abs'` := has_abs.abs
open is_absolute_value
open_locale classical big_operators nat complex_conjugate

section
open real is_absolute_value finset

section
variables {α : Type*} {β : Type*} [ring β]
  [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]

lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a)
  (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f :=
λ ε ε0,
let ⟨k, hk⟩ := archimedean.arch a ε0 in
have h : ∃ l, ∀ n ≥ m, a - l • ε < f n :=
  ⟨k + k + 1, λ n hnm, lt_of_lt_of_le
    (show a - (k + (k + 1)) • ε < -|f n|,
      from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin
        rw [neg_sub, lt_sub_iff_add_lt, add_nsmul, add_nsmul, one_nsmul],
        exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk
          (lt_add_of_pos_right _ ε0)),
      end))
    (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩,
let l := nat.find h in
have hl : ∀ (n : ℕ), n ≥ m → f n > a - l • ε := nat.find_spec h,
have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _))
  (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))),
begin
  cases not_forall.1
    (nat.find_min h (nat.pred_lt hl0)) with i hi,
  rw [not_imp, not_lt] at hi,
  existsi i,
  assume j hj,
  have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm hi.1 hj,
  rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'],
  calc f i ≤ a - (nat.pred l) • ε : hi.2
    ... = a - l • ε + ε :
      by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul',
        sub_add, add_sub_cancel] }
    ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _
end

lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a)
  (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f :=
begin
  refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _
    (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ :
      cau_seq α abs).2,
  ext,
  exact neg_neg _
end

end

section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
  [linear_ordered_field α] {abv : β → α} [is_absolute_value abv]

lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) :
  (∀ m, n ≤ m → abv (f m) ≤ g m) →
  is_cau_seq abs (λ n, ∑ i in range n, g i) →
  is_cau_seq abv (λ n, ∑ i in range n, f i) :=
begin
  assume hm hg ε ε0,
  cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
  existsi max n i,
  assume j ji,
  have hi₁ := hi j (le_trans (le_max_right n i) ji),
  have hi₂ := hi (max n i) (le_max_right n i),
  have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k)
    (∑ k in range (max n i), g k),
  have := add_lt_add hi₁ hi₂,
  rw [abs_sub_comm (∑ k in range (max n i), g k), add_halves ε] at this,
  refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this,
  generalize hk : j - max n i = k,
  clear this hi₂ hi₁ hi ε0 ε hg sub_le,
  rw tsub_eq_iff_eq_add_of_le ji at hk,
  rw hk,
  clear hk ji j,
  induction k with k' hi,
  { simp [abv_zero abv] },
  { simp only [nat.succ_add, sum_range_succ_comm, sub_eq_add_neg, add_assoc],
    refine le_trans (abv_add _ _ _) _,
    simp only [sub_eq_add_neg] at hi,
    exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi },
end

lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n))
  → is_cau_seq abv (λ m, ∑ n in range m, f n) :=
is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _)

end no_archimedean

section
variables {α : Type*} {β : Type*} [ring β]
  [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]

lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
   (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) :=
have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1,
is_cau_series_of_abv_cau
begin
  simp only [abv_pow abv] {eta := ff},
  have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) =
   λ m, geom_sum (abv x) m := rfl,
  simp only [this, geom_sum_eq hx1'] {eta := ff},
  conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] },
  refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _,
  { assume n hn,
    rw abs_of_nonneg,
    refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1)
      (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)),
    refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1),
    clear hn,
    induction n with n ih,
    { simp },
    { rw [pow_succ, ← one_mul (1 : α)],
      refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } },
  { assume n hn,
    refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _),
    rw [← one_mul (_ ^ n), pow_succ],
    exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) }
end

lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : |x| < 1) :
  is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) :=
have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) :=
  (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2,
by simpa only [mul_sum]

lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α)
  (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) :
  is_cau_seq abv (λ m, ∑ n in range m, f n) :=
have har1 : |r| < 1, by rwa abs_of_nonneg hr0,
begin
  refine is_cau_series_of_abv_le_cau n.succ _
    (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1),
  assume m hmn,
  cases classical.em (r = 0) with r_zero r_ne_zero,
  { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn,
    have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])),
    simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] },
  generalize hk : m - n.succ = k,
  have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero),
  replace hk : m = k + n.succ := (tsub_eq_iff_eq_add_of_le hmn).1 hk,
  induction k with k ih generalizing m n,
  { rw [hk, zero_add, mul_right_comm, inv_pow₀ _ _, ← div_eq_mul_inv, mul_div_cancel],
    exact (ne_of_lt (pow_pos r_pos _)).symm },
  { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp),
    rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc],
    exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn))
      (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) }
end

lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :
  ∑ m in range n, ∑ k in range (m + 1), f k (m - k) =
  ∑ m in range n, ∑ k in range (n - m), f m k :=
by rw [sum_sigma', sum_sigma']; exact sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
  have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
    mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
    mem_range.2 ((tsub_lt_tsub_iff_right (nat.le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
  have ha : a₁ < n ∧ a₂ ≤ a₁ :=
      ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
  have hb : b₁ < n ∧ b₂ ≤ b₁ :=
      ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
  have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
  have h' : a₁ = b₁ - b₂ + a₂ := (tsub_eq_iff_eq_add_of_le ha.2).1 (eq_of_heq h.2),
  sigma.mk.inj_iff.2
    ⟨tsub_add_cancel_of_le hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
      (heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
  have ha : a₁ < n ∧ a₂ < n - a₁ :=
      ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
  ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (lt_tsub_iff_right.1 ha.2),
    mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩,
  sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (add_tsub_cancel_right _ _).symm⟩⟩⟩)

-- TODO move to src/algebra/big_operators/basic.lean, rewrite with comm_group, and make to_additive
lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α}
  {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k =
  ∑ k in (range m).filter (λ k, n ≤ k), f k :=
begin
  rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)),
    sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'],
  refine finset.sum_congr
    (finset.ext $ λ a, ⟨λ h, by simp at *; finish,
    λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm,
      by simp * at *⟩)
    (λ _ _, rfl),
end

end

section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
  [linear_ordered_field α] {abv : β → α} [is_absolute_value abv]

lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) :
  abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp [abv_zero abv])
  (λ a s has ih, by rw [sum_insert has, sum_insert has];
    exact le_trans (abv_add abv _ _) (add_le_add_left ih _))

lemma cauchy_product {a b : ℕ → β}
  (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n)))
  (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) :
  ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) -
  ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε :=
let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in
let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in
have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0),
have hPε0 : 0 < ε / (2 * P),
  from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0),
let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in
have hQε0 : 0 < ε / (4 * Q),
  from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num)
    (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in
⟨2 * (max N M + 1), λ K hK,
have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) =
    ∑ m in range K, ∑ n in range (K - m), a m * b n,
  by simpa using sum_range_diag_flip K (λ m n, a m * b n),
have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k),
  by simp [finset.mul_sum],
have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k =
    ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k)
    + ∑ i in range K, a i * ∑ k in range K, b k,
  by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm],
have two_mul_two : (4 : α) = 2 * 2, by norm_num,
have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0,
have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0,
have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε,
  by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)),
    two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves],
have hNMK : max N M + 1 < K,
  from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK,
have hKN : N < K,
  from calc N ≤ max N M : le_max_left _ _
  ... < max N M + 1 : nat.lt_succ_self _
  ... < K : hNMK,
have hsumlesum : ∑ i in range (max N M + 1), abv (a i) *
      abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤
    ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)),
  from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left
    (le_of_lt (hN (K - m) K
      (le_tsub_of_add_le_left (le_trans
        (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ))
          (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK))
      (le_of_lt hKN))) (abv_nonneg abv _)),
have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P :=
  calc ∑ n in range (max N M + 1), abv (a n)
      = |∑ n in range (max N M + 1), abv (a n)| :
  eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x))))
  ... < P : hP (max N M + 1),
begin
  rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv],
  refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _,
  suffices : ∑ i in range (max N M + 1),
    abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) +
    (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) -
    ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) <
    ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
  { rw hε at this, simpa [abv_mul abv] },
  refine add_lt_add (lt_of_le_of_lt hsumlesum
    (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _,
  rw sum_range_sub_sum_range (le_of_lt hNMK),
  calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k),
      abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)
      ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) :
    sum_le_sum (λ n hn, begin
      refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _),
      rw sub_eq_add_neg,
      refine le_trans (abv_add _ _ _) _,
      rw [two_mul, abv_neg abv],
      exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)),
    end)
    ... < ε / (4 * Q) * (2 * Q) :
      by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)];
      refine (mul_lt_mul_right $ by rw two_mul;
        exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))
          (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2
        (lt_of_le_of_lt (le_abs_self _)
          (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK))
            (nat.le_succ_of_le (le_max_right _ _))))
end⟩

end no_archimedean

end

open finset

open cau_seq

namespace complex

lemma is_cau_abs_exp (z : ℂ) : is_cau_seq has_abs.abs
  (λ n, ∑ m in range n, abs (z ^ m / m!)) :=
let ⟨n, hn⟩ := exists_nat_gt (abs z) in
have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn,
series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0))
  (by rwa [div_lt_iff hn0, one_mul])
  (λ m hm,
    by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ,
      mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc,
      mul_div_right_comm, abs_mul, abs_div, abs_cast_nat];
    exact mul_le_mul_of_nonneg_right
      (div_le_div_of_le_left (abs_nonneg _) hn0
        (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _))

noncomputable theory

lemma is_cau_exp (z : ℂ) :
  is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) :=
is_cau_series_of_abv_cau (is_cau_abs_exp z)

/-- The Cauchy sequence consisting of partial sums of the Taylor series of
the complex exponential function -/
@[pp_nodot] def exp' (z : ℂ) :
  cau_seq ℂ complex.abs :=
⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩

/-- The complex exponential function, defined via its Taylor series -/
@[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z)

/-- The complex sine function, defined via `exp` -/
@[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2

/-- The complex cosine function, defined via `exp` -/
@[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2

/-- The complex tangent function, defined as `sin z / cos z` -/
@[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z

/-- The complex hyperbolic sine function, defined via `exp` -/
@[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2

/-- The complex hyperbolic cosine function, defined via `exp` -/
@[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2

/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/
@[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z

end complex

namespace real

open complex

/-- The real exponential function, defined as the real part of the complex exponential -/
@[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re

/-- The real sine function, defined as the real part of the complex sine -/
@[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re

/-- The real cosine function, defined as the real part of the complex cosine -/
@[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re

/-- The real tangent function, defined as the real part of the complex tangent -/
@[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re

/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/
@[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re

/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/
@[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re

/-- The real hypebolic tangent function, defined as the real part of
the complex hyperbolic tangent -/
@[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re

end real

namespace complex

variables (x y : ℂ)

@[simp] lemma exp_zero : exp 0 = 1 :=
lim_eq_of_equiv_const $
  λ ε ε0, ⟨1, λ j hj, begin
  convert ε0,
  cases j,
  { exact absurd hj (not_le_of_gt zero_lt_one) },
  { dsimp [exp'],
    induction j with j ih,
    { dsimp [exp']; simp },
    { rw ← ih dec_trivial,
      simp only [sum_range_succ, pow_succ],
      simp } }
end⟩

lemma exp_add : exp (x + y) = exp x * exp y :=
show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) =
  lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩)
  * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩),
from
have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! =
    ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!),
  from assume j,
    finset.sum_congr rfl (λ m hm, begin
      rw [add_pow, div_eq_mul_inv, sum_mul],
      refine finset.sum_congr rfl (λ i hi, _),
      have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2
        (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))),
      have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi),
      rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv₀, mul_inv₀],
      simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹,
        mul_comm (m.choose i : ℂ)],
      rw inv_mul_cancel h₁,
      simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm]
    end),
by rw lim_mul_lim;
  exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj];
    exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y)))

attribute [irreducible] complex.exp

lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l

lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s

lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod (multiplicative ℂ) α ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s

lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]

lemma exp_ne_zero : exp x ≠ 0 :=
λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp

lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add];
  simp [mul_inv_cancel (exp_ne_zero x)]

lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]

lemma exp_int_mul (z : ℂ) (n : ℤ) : complex.exp (n * z) = (complex.exp z) ^ n :=
begin
  cases n,
  { apply complex.exp_nat_mul },
  { simpa [complex.exp_neg, add_comm, ← neg_mul_eq_neg_mul_symm]
      using complex.exp_nat_mul (-z) (1 + n) },
end

@[simp] lemma exp_conj : exp (conj x) = conj (exp x) :=
begin
  dsimp [exp],
  rw [← lim_conj],
  refine congr_arg lim (cau_seq.ext (λ _, _)),
  dsimp [exp', function.comp, cau_seq_conj],
  rw star_ring_aut.map_sum,
  refine sum_congr rfl (λ n hn, _),
  rw [ring_equiv.map_div, ring_equiv.map_pow, ← of_real_nat_cast, conj_of_real]
end

@[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x :=
eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x :=
of_real_exp_of_real_re _

@[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 :=
by rw [← of_real_exp_of_real_re, of_real_im]

lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl

lemma two_sinh : 2 * sinh x = exp x - exp (-x) :=
mul_div_cancel' _ two_ne_zero'

lemma two_cosh : 2 * cosh x = exp x + exp (-x) :=
mul_div_cancel' _ two_ne_zero'

@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]

@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]

private lemma sinh_add_aux {a b c d : ℂ} :
  (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring

lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
begin
  rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
      exp_add, neg_add, exp_add, eq_comm,
      mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh,
      ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
      mul_left_comm, two_cosh, ← mul_assoc, two_cosh],
  exact sinh_add_aux
end

@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]

@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [add_comm, cosh, exp_neg]

private lemma cosh_add_aux {a b c d : ℂ} :
  (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring

lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
begin
  rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
      exp_add, neg_add, exp_add, eq_comm,
      mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh,
      ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
      mul_left_comm, two_cosh, mul_left_comm, two_sinh],
  exact cosh_add_aux
end

lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]

lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]

lemma sinh_conj : sinh (conj x) = conj (sinh x) :=
by rw [sinh, ← ring_equiv.map_neg, exp_conj, exp_conj, ← ring_equiv.map_sub, sinh,
  ring_equiv.map_div, conj_bit0, ring_equiv.map_one]

@[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x :=
eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x :=
of_real_sinh_of_real_re _

@[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 :=
by rw [← of_real_sinh_of_real_re, of_real_im]

lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl

lemma cosh_conj : cosh (conj x) = conj (cosh x) :=
begin
  rw [cosh, ← ring_equiv.map_neg, exp_conj, exp_conj, ← ring_equiv.map_add, cosh,
      ring_equiv.map_div, conj_bit0, ring_equiv.map_one]
end

@[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x :=
eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x :=
of_real_cosh_of_real_re _

@[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 :=
by rw [← of_real_cosh_of_real_re, of_real_im]

lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl

lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl

@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]

@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]

lemma tanh_conj : tanh (conj x) = conj (tanh x) :=
by rw [tanh, sinh_conj, cosh_conj, ← ring_equiv.map_div, tanh]

@[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x :=
eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x :=
of_real_tanh_of_real_re _

@[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 :=
by rw [← of_real_tanh_of_real_re, of_real_im]

lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl

lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
       two_cosh, two_sinh, add_add_sub_cancel, two_mul]

lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw [add_comm, cosh_add_sinh]

lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub,
       two_cosh, two_sinh, add_sub_sub_cancel, two_mul]

lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero]

lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 :=
begin
  rw ← cosh_sq_sub_sinh_sq x,
  ring
end

lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 :=
begin
  rw ← cosh_sq_sub_sinh_sq x,
  ring
end

lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw [two_mul, cosh_add, sq, sq]

lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
begin
  rw [two_mul, sinh_add],
  ring
end

lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
begin
  have h1 : x + 2 * x = 3 * x, by ring,
  rw [← h1, cosh_add x (2 * x)],
  simp only [cosh_two_mul, sinh_two_mul],
  have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring,
  rw [h2, sinh_sq],
  ring
end

lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
begin
  have h1 : x + 2 * x = 3 * x, by ring,
  rw [← h1, sinh_add x (2 * x)],
  simp only [cosh_two_mul, sinh_two_mul],
  have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring,
  rw [h2, cosh_sq],
  ring,
end

@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]

@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul]

lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I :=
mul_div_cancel' _ two_ne_zero'

lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) :=
mul_div_cancel' _ two_ne_zero'

lemma sinh_mul_I : sinh (x * I) = sin x * I :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
       ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one,
       neg_sub, neg_mul_eq_neg_mul]

lemma cosh_mul_I : cosh (x * I) = cos x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
       two_cos, neg_mul_eq_neg_mul]

lemma tanh_mul_I : tanh (x * I) = tan x * I :=
by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan]

lemma cos_mul_I : cos (x * I) = cosh x :=
by rw ← cosh_mul_I; ring_nf; simp

lemma sin_mul_I : sin (x * I) = sinh x * I :=
have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp },
by simpa only [neg_mul_eq_neg_mul_symm, div_I, neg_neg]
  using cancel_factors.cancel_factors_eq_div h I_ne_zero

lemma tan_mul_I : tan (x * I) = tanh x * I :=
by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh]

lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
       add_mul, add_mul, mul_right_comm, ← sinh_mul_I,
       mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add]

@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]

@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, sub_eq_add_neg, exp_neg, add_comm]

private lemma cos_add_aux {a b c d : ℂ} :
  (a + b) * (c + d) - (b - a) * (d - c) * (-1) =
  2 * (a * c + b * d) := by ring

lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I,
       sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I,
       mul_neg_one, sub_eq_add_neg]

lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]

lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]

lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I :=
by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc]

lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I :=
by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm

lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I :=
by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc]

lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I :=
by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm

theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
  have s1 := sin_add ((x + y) / 2) ((x - y) / 2),
  have s2 := sin_sub ((x + y) / 2) ((x - y) / 2),
  rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
  rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
  rw [s1, s2],
  ring
end

theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
  have s1 := cos_add ((x + y) / 2) ((x - y) / 2),
  have s2 := cos_sub ((x + y) / 2) ((x - y) / 2),
  rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
  rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
  rw [s1, s2],
  ring,
end

lemma sin_conj : sin (conj x) = conj (sin x) :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
       ← conj_neg_I, ← ring_equiv.map_mul, ← ring_equiv.map_mul, sinh_conj,
       mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm]

@[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x :=
eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x :=
of_real_sin_of_real_re _

@[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 :=
by rw [← of_real_sin_of_real_re, of_real_im]

lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl

lemma cos_conj : cos (conj x) = conj (cos x) :=
by rw [← cosh_mul_I, ← conj_neg_I, ← ring_equiv.map_mul, ← cosh_mul_I,
       cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg]

@[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x :=
eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x :=
of_real_cos_of_real_re _

@[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 :=
by rw [← of_real_cos_of_real_re, of_real_im]

lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl

@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]

lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl

lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]

@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]

lemma tan_conj : tan (conj x) = conj (tan x) :=
by rw [tan, sin_conj, cos_conj, ← ring_equiv.map_div, tan]

@[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x :=
eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real]

@[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x :=
of_real_tan_of_real_re _

@[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 :=
by rw [← of_real_tan_of_real_re, of_real_im]

lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl

lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) :=
by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I]

lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) :=
by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I]

@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
eq.trans
  (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm])
  (cosh_sq_sub_sinh_sq (x * I))

@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]

lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw [two_mul, cos_add, ← sq, ← sq]

lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x),
       ← sub_add, sub_add_eq_add_sub, two_mul]

lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw [two_mul, sin_add, two_mul, add_mul, mul_comm]

lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div]

lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']

lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel]

lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 :=
have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx,
by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] }

lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) :
  tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]

lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
begin
  have h1 : x + 2 * x = 3 * x, by ring,
  rw [← h1, cos_add x (2 * x)],
  simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, sq],
  have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring,
  rw [h2, cos_sq'],
  ring
end

lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
begin
  have h1 : x + 2 * x = 3 * x, by ring,
  rw [← h1, sin_add x (2 * x)],
  simp only [cos_two_mul, sin_two_mul, cos_sq'],
  have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring,
  rw [h2, cos_sq'],
  ring
end

lemma exp_mul_I : exp (x * I) = cos x + sin x * I :=
(cos_add_sin_I _).symm

lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) :=
by rw [exp_add, exp_mul_I]

lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) :=
by rw [← exp_add_mul_I, re_add_im]

lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im :=
by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] }

lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im :=
by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] }

@[simp] lemma exp_of_real_mul_I_re (x : ℝ) : (exp (x * I)).re = real.cos x :=
by simp [exp_mul_I, cos_of_real_re]

@[simp] lemma exp_of_real_mul_I_im (x : ℝ) : (exp (x * I)).im = real.sin x :=
by simp [exp_mul_I, sin_of_real_re]

/-- **De Moivre's formula** -/
theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) :
  (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I :=
begin
  rw [← exp_mul_I, ← exp_mul_I],
  induction n with n ih,
  { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] },
  { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] }
end

end complex

namespace real

open complex

variables (x y : ℝ)

@[simp] lemma exp_zero : exp 0 = 1 :=
by simp [real.exp]

lemma exp_add : exp (x + y) = exp x * exp y :=
by simp [exp_add, exp]

lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l

lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s

lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod (multiplicative ℝ) α ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s

lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]

lemma exp_ne_zero : exp x ≠ 0 :=
λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at *

lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg,
  of_real_inv, of_real_exp]

lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]

@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]

@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]

lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← of_real_inj]; simp [sin, sin_add]

@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]

@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]

lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw ← of_real_inj; simp [cos, cos_add]

lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]

lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]

lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
  rw ← of_real_inj,
  simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul,
    of_real_one, of_real_bit0],
  convert sin_sub_sin _ _;
  norm_cast
end

theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
  rw ← of_real_inj,
  simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add,
    of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0],
  convert cos_sub_cos _ _,
  ring,
end

lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2)  * cos ((x - y) / 2) :=
begin
  rw ← of_real_inj,
  simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul,
    of_real_one, of_real_bit0],
  convert cos_add_cos _ _;
  norm_cast,
end

lemma tan_eq_sin_div_cos : tan x = sin x / cos x :=
by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos]

lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]

@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]

@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]

@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
of_real_inj.1 $ by simp

@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]

lemma sin_sq_le_one : sin x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (sq_nonneg _)

lemma cos_sq_le_one : cos x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (sq_nonneg _)

lemma abs_sin_le_one : |sin x| ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, sin_sq_le_one]

lemma abs_cos_le_one : |cos x| ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, cos_sq_le_one]

lemma sin_le_one : sin x ≤ 1 :=
(abs_le.1 (abs_sin_le_one _)).2

lemma cos_le_one : cos x ≤ 1 :=
(abs_le.1 (abs_cos_le_one _)).2

lemma neg_one_le_sin : -1 ≤ sin x :=
(abs_le.1 (abs_sin_le_one _)).1

lemma neg_one_le_cos : -1 ≤ cos x :=
(abs_le.1 (abs_cos_le_one _)).1

lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw ← of_real_inj; simp [cos_two_mul]

lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw ← of_real_inj; simp [cos_two_mul']

lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw ← of_real_inj; simp [sin_two_mul]

lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
of_real_inj.1 $ by simpa using cos_sq x

lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']

lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 :=
eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _

lemma abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) :
  |sin x| = sqrt (1 - cos x ^ 2) :=
by rw [← sin_sq, sqrt_sq_eq_abs]

lemma abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) :
  |cos x| = sqrt (1 - sin x ^ 2) :=
by rw [← cos_sq', sqrt_sq_eq_abs]

lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2  :=
have complex.cos x ≠ 0, from mt (congr_arg re) hx,
of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this

lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) :
  tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]

lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
  (sqrt (1 + tan x ^ 2))⁻¹ = cos x :=
by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne']

lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
  tan x / sqrt (1 + tan x ^ 2) = sin x :=
by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv]

lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
by rw ← of_real_inj; simp [cos_three_mul]

lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
by rw ← of_real_inj; simp [sin_three_mul]

/-- The definition of `sinh` in terms of `exp`. -/
lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two,
    ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re]

@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]

@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]

lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
by rw ← of_real_inj; simp [sinh_add]

/-- The definition of `cosh` in terms of `exp`. -/
lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two,
    ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re]

@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]

@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]

lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
by rw ← of_real_inj; simp [cosh, cosh_add]

lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]

lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]

lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x :=
of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh]

@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]

@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]

lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw ← of_real_inj; simp [cosh_add_sinh]

lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw ← of_real_inj; simp [sinh_add_cosh]

lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq]

lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 :=
by rw ← of_real_inj; simp [cosh_sq]

lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 :=
by rw ← of_real_inj; simp [sinh_sq]

lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw ← of_real_inj; simp [cosh_two_mul]

lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
by rw ← of_real_inj; simp [sinh_two_mul]

lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
by rw ← of_real_inj; simp [cosh_three_mul]

lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
by rw ← of_real_inj; simp [sinh_three_mul]

open is_absolute_value

/-- This is an intermediate result that is later replaced by `real.add_one_le_exp`; use that lemma
instead. -/
lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x :=
calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ has_abs.abs) :
  le_lim (cau_seq.le_of_exists ⟨2,
    λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re,
      from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp,
      have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp,
      begin
        rw [← tsub_add_cancel_of_le hj, sum_range_succ', sum_range_succ',
          add_re, add_re, h₁, h₂, add_assoc,
          ← coe_re_add_group_hom, (re_add_group_hom).map_sum, coe_re_add_group_hom ],
        refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _),
        rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re],
        exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _),
      end⟩)
... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re]

lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x :=
by linarith [add_one_le_exp_of_nonneg hx]

lemma exp_pos (x : ℝ) : 0 < exp x :=
(le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp)
  (λ h, by rw [← neg_neg x, real.exp_neg];
    exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h))))

@[simp] lemma abs_exp (x : ℝ) : |exp x| = exp x :=
abs_of_pos (exp_pos _)

lemma exp_strict_mono : strict_mono exp :=
λ x y h, by rw [← sub_add_cancel y x, real.exp_add];
  exact (lt_mul_iff_one_lt_left (exp_pos _)).2
    (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith)))

@[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone

@[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt

@[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le

lemma exp_injective : function.injective exp := exp_strict_mono.injective

@[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff

@[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 :=
by rw [← exp_zero, exp_injective.eq_iff]

@[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x :=
by rw [← exp_zero, exp_lt_exp]

@[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 :=
by rw [← exp_zero, exp_lt_exp]

@[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 :=
exp_zero ▸ exp_le_exp

@[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x :=
exp_zero ▸ exp_le_exp

/-- `real.cosh` is always positive -/
lemma cosh_pos (x : ℝ) : 0 < real.cosh x :=
(cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x)))

end real

namespace complex

lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) :
  ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) :=
calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α)
    = ∑ m in range (j - n), 1 / (m + n)! :
  sum_bij (λ m _, m - n)
    (λ m hm, mem_range.2 $ (tsub_lt_tsub_iff_right (by simp at hm; tauto)).2
      (by simp at hm; tauto))
    (λ m hm, by rw tsub_add_cancel_of_le; simp at *; tauto)
    (λ a₁ a₂ ha₁ ha₂ h,
      by rwa [tsub_eq_iff_eq_add_of_le, tsub_add_eq_add_tsub, eq_comm, tsub_eq_iff_eq_add_of_le,
              add_left_inj, eq_comm] at h;
        simp at *; tauto)
    (λ b hb, ⟨b + n,
      mem_filter.2 ⟨mem_range.2 $ lt_tsub_iff_right.mp (mem_range.1 hb), nat.le_add_left _ _⟩,
      by rw add_tsub_cancel_right⟩)
... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ :
  begin
    refine  sum_le_sum (assume m n, _),
    rw [one_div, inv_le_inv],
    { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm],
      exact nat.factorial_mul_pow_le_factorial },
    { exact nat.cast_pos.2 (nat.factorial_pos _) },
    { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _))
        (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) },
  end
... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m :
  by simp [mul_inv₀, mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow₀]
... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) :
  have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1
        (mt nat.succ.inj (pos_iff_ne_zero.1 hn)),
  have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _),
  have h₃ : (n! * n : α) ≠ 0,
    from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _)))
    (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)),
  have h₄ : (n.succ - 1 : α) = n, by simp,
  by rw [← geom_sum_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃,
      mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev₀, h₄,
      ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃];
    simp [mul_add, add_mul, mul_assoc, mul_comm]
... ≤ n.succ / (n! * n) :
  begin
    refine iff.mpr (div_le_div_right (mul_pos _ _)) _,
    exact nat.cast_pos.2 (nat.factorial_pos _),
    exact nat.cast_pos.2 hn,
    exact sub_le_self _
      (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _))
  end

lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) :
  abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :=
begin
  rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
  refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
  simp_rw ← sub_eq_add_neg,
  show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!)
    ≤ abs x ^ n * (n.succ * (n! * n)⁻¹),
  rw sum_range_sub_sum_range hj,
  calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ))
      = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) :
    begin
      refine congr_arg abs (sum_congr rfl (λ m hm, _)),
      rw [mem_filter, mem_range] at hm,
      rw [← mul_div_assoc, ← pow_add, add_tsub_cancel_of_le hm.2]
    end
  ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _
  ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) :
    begin
      refine sum_le_sum (λ m hm, _),
      rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat],
      refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _,
      { exact nat.cast_pos.2 (nat.factorial_pos _), },
      { rw abv_pow abs,
        exact (pow_le_one _ (abs_nonneg _) hx), },
      { exact pow_nonneg (abs_nonneg _) _ },
    end
  ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) :
    by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm]
  ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :
    mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _)
end

lemma exp_bound' {x : ℂ} {n : ℕ} (hx : abs x / (n.succ) ≤ 1 / 2) :
  abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2 :=
begin
  rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
  refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
  simp_rw [←sub_eq_add_neg],
  show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2,
  let k := j - n,
  have hj : j = n + k := (add_tsub_cancel_of_le hj).symm,
  rw [hj, sum_range_add_sub_sum_range],
  calc abs (∑ (i : ℕ) in range k, x ^ (n + i) / ((n + i)! : ℂ))
      ≤ ∑ (i : ℕ) in range k, abs (x ^ (n + i) / ((n + i)! : ℂ)) : abv_sum_le_sum_abv _ _
  ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n + i)! :
        by simp only [complex.abs_cast_nat, complex.abs_div, abv_pow abs]
  ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n! * n.succ ^ i) : _
  ... = ∑ (i : ℕ) in range k, (abs x) ^ (n) / (n!) * ((abs x)^i / n.succ ^ i) : _
  ... ≤ abs x ^ n / (↑n!) * 2 : _,
  { refine sum_le_sum (λ m hm, div_le_div (pow_nonneg (abs_nonneg x) (n + m)) (le_refl _) _ _),
    { exact_mod_cast mul_pos n.factorial_pos (pow_pos n.succ_pos _), },
    { exact_mod_cast (nat.factorial_mul_pow_le_factorial), }, },
  { refine finset.sum_congr rfl (λ _ _, _),
    simp only [pow_add, div_eq_inv_mul, mul_inv₀, mul_left_comm, mul_assoc], },
  { rw [←mul_sum],
    apply mul_le_mul_of_nonneg_left,
    { simp_rw [←div_pow],
      rw [←geom_sum_def, geom_sum_eq, div_le_iff_of_neg],
      { transitivity (-1 : ℝ),
        { linarith },
        { simp only [neg_le_sub_iff_le_add, div_pow, nat.cast_succ, le_add_iff_nonneg_left],
          exact div_nonneg (pow_nonneg (abs_nonneg x) k) (pow_nonneg (n+1).cast_nonneg k) } },
      { linarith },
      { linarith }, },
    { exact div_nonneg (pow_nonneg (abs_nonneg x) n) (nat.cast_nonneg (n!)), }, },
end

lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) :
  abs (exp x - 1) ≤ 2 * abs x :=
calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) :
  by simp [sum_range_succ]
... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) :
  exp_bound hx dec_trivial
... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm]

lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) :
  abs (exp x - 1 - x) ≤ (abs x)^2 :=
calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) :
  by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc]
... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) :
  exp_bound hx dec_trivial
... ≤ (abs x)^2 * 1 :
  mul_le_mul_of_nonneg_left (by norm_num) (sq_nonneg (abs x))
... = (abs x)^2 :
  by rw [mul_one]

end complex

namespace real

open complex finset

lemma exp_bound {x : ℝ} (hx : |x| ≤ 1) {n : ℕ} (hn : 0 < n) :
  |exp x - ∑ m in range n, x ^ m / m!|≤ |x| ^ n * (n.succ / (n! * n)) :=
begin
  have hxc : complex.abs x ≤ 1, by exact_mod_cast hx,
  convert exp_bound hxc hn; norm_cast
end

lemma exp_bound' {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) {n : ℕ} (hn : 0 < n) :
  real.exp x ≤ ∑ m in finset.range n, x ^ m / m! + x ^ n * (n + 1) / (n! * n) :=
begin
  have h3 : |x| = x := by simpa,
  have h4 : |x| ≤ 1 := by rwa h3,
  have h' := real.exp_bound h4 hn,
  rw h3 at h',
  have h'' := (abs_sub_le_iff.1 h').1,
  have t := sub_le_iff_le_add'.1 h'',
  simpa [mul_div_assoc] using t
end

/-- A finite initial segment of the exponential series, followed by an arbitrary tail.
For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function
of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`,
for any `r`. -/
def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r

@[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near]

@[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) :=
by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv,
  mul_inv₀]; ac_refl

theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) :=
by simp [exp_near, mul_sub]

lemma exp_approx_end (n m : ℕ) (x : ℝ)
  (e₁ : n + 1 = m) (h : |x| ≤ 1) :
  |exp x - exp_near m x 0| ≤ |x| ^ m / m! * ((m+1)/m) :=
by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith }

lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ)
  (e₁ : n + 1 = m) (a₂ b₂ : ℝ)
  (e : |1 + x / m * a₂ - a₁| ≤ b₁ - |x| / m * b₂)
  (h : |exp x - exp_near m x a₂| ≤ |x| ^ m / m! * b₂) :
  |exp x - exp_near n x a₁| ≤ |x| ^ n / n! * b₁ :=
begin
  refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _),
  subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul],
  convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _,
  { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv₀],
    ac_refl },
  { simp [_root_.div_nonneg, _root_.abs_nonneg] }
end

lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ)
  (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : |x| ≤ 1)
  (e : |1 - a| ≤ b - |x| / rm * ((rm+1)/rm)) :
  |exp x - exp_near n x a| ≤ |x| ^ n / n! * b :=
by subst er; exact
exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h)

lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ}
  (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm)
  (h : |exp 1 - exp_near m 1 ((a₁ - 1) * rm)| ≤ |1| ^ m / m! * (b₁ * rm)) :
  |exp 1 - exp_near n 1 a₁| ≤ |1| ^ n / n! * b₁ :=
begin
  subst er,
  refine exp_approx_succ _ en _ _ _ h,
  field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith],
end

lemma exp_approx_start (x a b : ℝ)
  (h : |exp x - exp_near 0 x a| ≤ |x| ^ 0 / 0! * b) :
  |exp x - a| ≤ b :=
by simpa using h

lemma cos_bound {x : ℝ} (hx : |x| ≤ 1) :
  |cos x - (1 - x ^ 2 / 2)| ≤ |x| ^ 4 * (5 / 96) :=
calc |cos x - (1 - x ^ 2 / 2)| = abs (complex.cos x - (1 - x ^ 2 / 2)) :
  by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) :
  by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)]
... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) +
    ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) :
  congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
    simp only [sum_range_succ],
    simp [pow_succ],
    apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
  end)
... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) +
    abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) :
  by rw add_div; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
    abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
  by simp [complex.abs_div]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
    (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2)  :
  add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
             ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]

lemma sin_bound {x : ℝ} (hx : |x| ≤ 1) :
  |sin x - (x - x ^ 3 / 6)| ≤ |x| ^ 4 * (5 / 96) :=
calc |sin x - (x - x ^ 3 / 6)| = abs (complex.sin x - (x - x ^ 3 / 6)) :
  by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) :
  by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _),
    div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num]
... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) -
    (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) :
  congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
    simp only [sum_range_succ],
    simp [pow_succ],
    apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
  end)
... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) +
    abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) :
  by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
    abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
  by simp [add_comm, complex.abs_div, complex.abs_mul]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
    (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) :
  add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
             ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]

lemma cos_pos_of_le_one {x : ℝ} (hx : |x| ≤ 1) : 0 < cos x :=
calc 0 < (1 - x ^ 2 / 2) - |x| ^ 4 * (5 / 96) :
  sub_pos.2 $ lt_sub_iff_add_lt.2
    (calc |x| ^ 4 * (5 / 96) + x ^ 2 / 2
          ≤ 1 * (5 / 96) + 1 / 2 :
        add_le_add
          (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num))
          ((div_le_div_right (by norm_num)).2 (by rw [sq, ← abs_mul_self, _root_.abs_mul];
            exact mul_le_one hx (abs_nonneg _) hx))
      ... < 1 : by norm_num)
... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2

lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x :=
calc 0 < x - x ^ 3 / 6 - |x| ^ 4 * (5 / 96) :
  sub_pos.2 $ lt_sub_iff_add_lt.2
    (calc |x| ^ 4 * (5 / 96) + x ^ 3 / 6
        ≤ x * (5 / 96) + x / 6 :
      add_le_add
        (mul_le_mul_of_nonneg_right
          (calc |x| ^ 4 ≤ |x| ^ 1 : pow_le_pow_of_le_one (abs_nonneg _)
                (by rwa _root_.abs_of_nonneg (le_of_lt hx0))
                dec_trivial
            ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num))
        ((div_le_div_right (by norm_num)).2
          (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial
            ... = x : pow_one _))
    ... < x : by linarith)
... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound
    (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2

lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x :=
have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa),
calc 0 < 2 * sin (x / 2) * cos (x / 2) :
  mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this))
    (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))]))
... = sin x : by rw [← sin_two_mul, two_mul, add_halves]

lemma cos_one_le : cos 1 ≤ 2 / 3 :=
calc cos 1 ≤ |(1 : ℝ)| ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) :
  sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1
... ≤ 2 / 3 : by norm_num

lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (le_of_eq abs_one)

lemma cos_two_neg : cos 2 < 0 :=
calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm
  ... = _ : real.cos_two_mul 1
  ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left
          (by { rw [sq, sq], exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le })
          zero_le_two) _
  ... < 0 : by norm_num

lemma exp_bound_div_one_sub_of_interval_approx  {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) :
  ∑ (j : ℕ) in finset.range 3, x ^ j / (j.factorial)
  + x ^ 3 * ((3 : ℕ) + 1) / ((3 : ℕ).factorial * (3 : ℕ))
  ≤ ∑ j in (finset.range 3), x ^ j :=
begin
  norm_num [finset.sum],
  rw [add_assoc, add_comm (x + 1) (x ^ 3 * 4 / 18), ← add_assoc, add_le_add_iff_right,
      ← add_le_add_iff_left (-(x ^ 2 / 2)), ← add_assoc, comm_ring.add_left_neg (x ^ 2 / 2),
      zero_add, neg_add_eq_sub, sub_half, sq, pow_succ, sq],
  have i1 : x * 4 / 18 ≤ 1 / 2 := by linarith,
  have i2 : 0 ≤ x * 4 / 18 := by linarith,
  have i3 := mul_le_mul h1 h1 le_rfl h1,
  rw zero_mul at i3,
  have t := mul_le_mul le_rfl i1 i2 i3,
  rw ← mul_assoc,
  rwa [mul_one_div, ← mul_div_assoc, ← mul_assoc] at t,
end

lemma exp_bound_div_one_sub_of_interval {x : ℝ} (h1 : 0 ≤ x) (h2 : x < 1) :
  real.exp x ≤ 1 / (1 - x) :=
begin
  have h : ∑ j in (finset.range 3), x ^ j ≤ 1 / (1 - x),
  { norm_num [finset.sum],
    have h1x : 0 < 1 - x := by simpa,
    rw le_div_iff h1x,
    norm_num [← add_assoc, mul_sub_left_distrib, mul_one, add_mul,
              sub_add_eq_sub_sub, pow_succ' x 2],
    have hx3 : 0 ≤ x ^ 3,
    { norm_num,
      exact h1 },
    linarith },
  exact (exp_bound' h1 h2.le $ by linarith).trans
        ((exp_bound_div_one_sub_of_interval_approx h1 h2.le).trans h),
end

lemma one_sub_le_exp_minus_of_pos {y : ℝ} (h : 0 ≤ y) : 1 - y ≤ real.exp (-y) :=
begin
  rw real.exp_neg,
  have r1 : (1 - y) * (real.exp y) ≤ 1,
  { cases le_or_lt (1 - y) 0,
    { have h'' : (1 - y) * y.exp ≤ 0,
      { rw mul_nonpos_iff,
        right,
        exact ⟨h_1, y.exp_pos.le⟩ },
    linarith },
    have hy1 : y < 1 := by linarith,
    rw  ← le_div_iff' h_1,
    exact exp_bound_div_one_sub_of_interval h hy1 },
  rw inv_eq_one_div,
  rw le_div_iff' y.exp_pos,
  rwa mul_comm at r1,
end

lemma add_one_le_exp_of_nonpos {x : ℝ} (h : x ≤ 0) : x + 1 ≤ real.exp x :=
begin
  rw add_comm,
  have h1 : 0 ≤ -x := by linarith,
  simpa using one_sub_le_exp_minus_of_pos h1
end

lemma add_one_le_exp (x : ℝ) : x + 1 ≤ real.exp x :=
begin
  cases le_or_lt 0 x,
  { exact real.add_one_le_exp_of_nonneg h },
  exact add_one_le_exp_of_nonpos h.le,
end

end real

namespace complex

@[simp] lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 :=
have _ := real.sin_sq_add_cos_sq x,
by simp [add_comm, abs, norm_sq, sq, *, sin_of_real_re, cos_of_real_re, mul_re] at *

@[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x :=
by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _))

@[simp] lemma abs_exp_of_real_mul_I (x : ℝ) : abs (exp (x * I)) = 1 :=
by rw [exp_mul_I, abs_cos_add_sin_mul_I]

lemma abs_exp (z : ℂ) : abs (exp z) = real.exp (z.re) :=
by rw [exp_eq_exp_re_mul_sin_add_cos, abs_mul, abs_exp_of_real, abs_cos_add_sin_mul_I, mul_one]

lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re :=
by rw [abs_exp, abs_exp, real.exp_eq_exp]

end complex


import data.hash_map

universe u

namespace tactic

meta def at_target (tac : expr → tactic (expr × expr)) : tactic unit :=
  do tgt ← target,
     (new_tgt, pf) ← tac tgt,
     n ← mk_fresh_name,
     assert n new_tgt, swap,
     ht ← get_local n,
     mk_app `eq.mpr [pf, ht] >>= exact

meta def fsimpt (ns : list name) (tac : tactic unit) : tactic unit := do
  s ← list.mfoldl (λ slss n, simp_lemmas.add_simp slss n) simp_lemmas.mk ns,
  at_target (λ e, do (a, new_e, pf) ← ext_simplify_core () {} s
                                                        (λ u, failed)
                                                        (λ a s r p e, failed)
                                                        (λ a s r p e, do ⟨u, new_e, pr⟩ ← conv.apply_lemmas_core s tac r e,
                                                                         return ((), new_e, pr, tt))
                                                        `eq e,
                     return (new_e, pf))
end tactic
namespace list
variable {α : Type u}

def dnth [decidable_eq α] [inhabited α] (xs : list α) (n : ℕ) : α :=
match xs^.nth n with
| (some x) := x
| none     := default α
end

def at_nth (xs : list α) (idx : ℕ) (x : α) : Prop := nth xs idx = some x

def set_nth : list α → ℕ → α → option (list α)
| (x::xs) 0     a := some (a :: xs)
| (x::xs) (i+1) a := do ys ← set_nth xs i a, return (x :: ys)
| []      _     _ := none

instance decidable_subset [decidable_eq α] (xs ys : list α) : decidable (xs ⊆ ys) :=
begin
simp [has_subset.subset, list.subset],
apply_instance
end

lemma subset_trans [decidable_eq α] {xs zs : list α} (ys : list α) : xs ⊆ ys → ys ⊆ zs → xs ⊆ zs := sorry
lemma subset_union_left [decidable_eq α] (xs ys zs : list α) : xs ⊆ ys → xs ⊆ ys ∪ zs := sorry
lemma subset_union_right [decidable_eq α] (xs ys zs : list α) : xs ⊆ zs → xs ⊆ ys ∪ zs := sorry

lemma subset_pre_union_left [decidable_eq α] {xs ys zs : list α} : xs ∪ ys ⊆ zs → xs ⊆ zs := sorry
lemma subset_pre_union_right [decidable_eq α] {xs ys zs : list α} : xs ∪ ys ⊆ zs → ys ⊆ zs := sorry

lemma subset_union_trans_right [decidable_eq α] {xs ys zs} (ws : list α) : zs ⊆ ws → xs ⊆ ys ∪ zs → xs ⊆ ys ∪ ws := sorry
lemma subset_union_trans_left [decidable_eq α] {xs ys zs} (ws : list α) : ys ⊆ ws → xs ⊆ ys ∪ zs → xs ⊆ ws ∪ zs := sorry

lemma remove_all_subset [decidable_eq α] (xs ys zs : list α) : xs ⊆ zs → remove_all xs ys ⊆ zs := sorry

lemma at_nth_of_dnth_lt [decidable_eq α] [inhabited α] {xs : list α} {idx : ℕ} :
  idx < length xs → at_nth xs idx (dnth xs idx) := sorry

lemma at_nth_of_len {xs ys : list α} {x : α} {k : ℕ} : k = length xs → at_nth (xs ++ x :: ys) k x := sorry

lemma mem_of_singleton_subset [decidable_eq α] -- TODO(dhs): current spot
H_ss : [v] ⊆ L
⊢ v ∈ L

end list

namespace hash_map

def dfind {α : Type*} [decidable_eq α] {β : α → Type*} [∀ a, inhabited (β a)] (m : hash_map α β) (a : α) : β a :=
match m^.find a with
| (some b) := b
| none     := default (β a)
end

end hash_map

def hash_set (α : Type u) [decidable_eq α] : Type u :=
hash_map α (λ x : α, unit)

namespace hash_set

variables {α : Type u} [decidable_eq α]

def insert (s : hash_set α) (x : α) : hash_set α :=
hash_map.insert s x ()

def contains (s : hash_set α) (x : α) : bool :=
(hash_map.find s x).is_some

instance : has_mem α (hash_set α) := ⟨λa m, m.contains a⟩

end hash_set

section seq
variables {α : Type*} (rel : α → α → Prop)

inductive star : α → α → Prop
| rfl    : ∀ (x : α), star x x
| rtrans : ∀ (x y z : α), rel x y → star y z → star x y

end seq

namespace star
variables {α : Type*} (rel : α → α → Prop)

lemma trans (x y z : α) : star rel x y → star rel y z → star rel x z := sorry

end star

namespace compiler
open tactic list

structure var : Type := (id : ℕ)

namespace var
instance : decidable_eq var := by mk_dec_eq_instance
end var

@[reducible] def vstate : Type := hash_map var (λ v : var, ℕ)
def empty_vstate : vstate := mk_hash_map (λ v : var, v^.id)

inductive aexp : Type
| aconst : ℕ → aexp
| avar   : var → aexp
| aadd   : aexp → aexp → aexp
| asub   : aexp → aexp → aexp
| amul   : aexp → aexp → aexp

inductive bexp : Type
| btrue  : bexp
| bfalse : bexp
| bnot   : bexp → bexp
| band   : bexp → bexp → bexp
| beq    : aexp → aexp → bexp
| ble    : aexp → aexp → bexp

def aeval (st : vstate) : aexp → ℕ
| (aexp.aconst n) := n
| (aexp.avar v) := st^.dfind v
| (aexp.aadd e₁ e₂) := aeval e₁ + aeval e₂
| (aexp.asub e₁ e₂) := aeval e₁ - aeval e₂
| (aexp.amul e₁ e₂) := aeval e₁ * aeval e₂

def beval (st : vstate) : bexp → bool
| (bexp.btrue)      := tt
| (bexp.bfalse)     := ff
| (bexp.bnot b)     := bnot (beval b)
| (bexp.band b₁ b₂) := beval b₁ && beval b₂
| (bexp.beq e₁ e₂)  := aeval st e₁ = aeval st e₂
| (bexp.ble e₁ e₂)  := aeval st e₁ ≤ aeval st e₂

inductive com : Type
| cskip  : com
| cass   : var → aexp → com
| cseq   : com → com → com
| cif    : bexp → com → com → com
| cwhile : bexp → com → com

open com

inductive ceval : com → vstate → vstate → Prop
| eskip : ∀ st, ceval cskip st st
| eass  : ∀ st a n x, aeval st a = n → ceval (cass x a) st (st^.insert x n)
| eseq : ∀ c₁ c₂ st₁ st₂ st₃, ceval c₁ st₁ st₂ → ceval c₂ st₂ st₃ → ceval (cseq c₁ c₂) st₁ st₃
| eift : ∀ st₁ st₂ b c₁ c₂, beval st₁ b = tt → ceval c₁ st₁ st₂ → ceval (cif b c₁ c₂) st₁ st₂
| eiff : ∀ st₁ st₂ b c₁ c₂, beval st₁ b = ff → ceval c₂ st₁ st₂ → ceval (cif b c₁ c₂) st₁ st₂
| ewhilet : ∀ st₁ st₂ st₃ b c, beval st₁ b = tt → ceval c st₁ st₂ → ceval (cwhile b c) st₂ st₃ → ceval (cwhile b c) st₁ st₃
| ewhilef : ∀ st b c, beval st b = ff → ceval (cwhile b c) st st

open ceval

def fv_aexp : aexp → list var
| (aexp.aconst n) := []
| (aexp.avar v)   := [v]
| (aexp.aadd e₁ e₂) := fv_aexp e₁ ∪ fv_aexp e₂
| (aexp.asub e₁ e₂) := fv_aexp e₁ ∪ fv_aexp e₂
| (aexp.amul e₁ e₂) := fv_aexp e₁ ∪ fv_aexp e₂

def fv_bexp : bexp → list var
| (bexp.btrue)      := []
| (bexp.bfalse)     := []
| (bexp.bnot b)     := fv_bexp b
| (bexp.band b₁ b₂) := fv_bexp b₁ ∪ fv_bexp b₂
| (bexp.beq e₁ e₂)  := fv_aexp e₁ ∪ fv_aexp e₂
| (bexp.ble e₁ e₂)  := fv_aexp e₁ ∪ fv_aexp e₂

def fv_com : com → list var
| cskip         := []
| (cass x e)    := fv_aexp e
| (cseq c₁ c₂)  := fv_com c₁ ∪ fv_com c₂
| (cif b c₁ c₂) := fv_bexp b ∪ fv_com c₁ ∪ fv_com c₂
| (cwhile b c)  := fv_bexp b ∪ fv_com c

section fixpoint

parameter (F : list var → list var)
parameter (dflt : list var)

def iterate : ℕ → list var → list var
| 0     _ := dflt
| (n+1) x := let x' := F x in (if x' ⊆ x then x else iterate n x')

lemma iterate_charact : ∀ (niter : ℕ) (start : list var), F (iterate niter start) ⊆ (iterate niter start) ∨ (iterate niter start) = dflt
| 0           _     := or.inr rfl
| (niter + 1) start :=
begin
simp only [iterate],
have H_em : F start ⊆ start ∨ ¬ (F start ⊆ start) := decidable.em _,
cases H_em with H_ss H_n_ss,
{ simp only [H_ss, if_pos, if_simp_congr], left, triv },
{ simp only [H_n_ss, if_neg, if_simp_congr, if_false], apply iterate_charact }
end

def fixpoint : list var := iterate 10 []

lemma fixpoint_charact : (F fixpoint ⊆ fixpoint) ∨ (fixpoint = dflt) :=
by apply iterate_charact

variable (F_stable : ∀ x, x ⊆ dflt → F x ⊆ dflt)
include F_stable

lemma iterate_upper_bound : ∀ (niter : ℕ) (start : list var), start ⊆ dflt → iterate niter start ⊆ dflt
| 0         start := by { simp [iterate] }
| (niter+1) start :=
begin
simp [iterate],
have H_em : F start ⊆ start ∨ ¬ (F start ⊆ start) := decidable.em _,
cases H_em with H_ss H_n_ss,
{ simp [H_ss], intro H, exact H },
{ simp [H_n_ss], intro H, apply iterate_upper_bound, exact F_stable _ H }
end

lemma fixpoint_upper_bound : fixpoint ⊆ dflt :=
begin
apply iterate_upper_bound,
exact F_stable,
apply nil_subset
end

end fixpoint

/- Liveness analysis. -/

/- [L] is the set of variables live "after" command [c].
  The result of [live c L] is the set of variables live "before" [c]. -/

def live : com → list var → list var
| cskip         L := L
| (cass x e)    L := if x ∈ L then remove_all L [x] else fv_aexp e
| (cseq c₁ c₂)  L := live c₁ (live c₂ L)
| (cif b c₁ c₂) L := fv_bexp b ∪ live c₁ L ∪ live c₂ L
| (cwhile b c)  L := let L' := fv_bexp b ∪ L,
                         dflt := fv_com (cwhile b c) ∪ L
                     in  fixpoint (λ x, L' ∪ live c x) dflt

lemma live_upper_bound : ∀ (c : com) (L : list var), live c L ⊆ fv_com c ∪ L
| cskip         L :=
begin
simp [live],
apply subset_union_right, apply subset.refl
end

| (cass x e)    L :=
begin
simp [live, fv_com],
have H_em : x ∈ L ∨ ¬ (x ∈ L) := decidable.em _,
cases H_em with H_mem H_nmem,
{ simp [H_mem], apply subset_union_right, apply remove_all_subset, apply subset.refl },
{ simp [H_nmem], apply subset_union_left, apply subset.refl }
end

| (cseq c₁ c₂)  L :=
begin
simp [live, fv_com],
have H₁ : live c₂ L ⊆ fv_com c₂ ∪ L := by apply live_upper_bound,
have H₂ : live c₁ (live c₂ L) ⊆ fv_com c₁ ∪ live c₂ L := by apply live_upper_bound,
exact sorry -- TODO(dhs): simple but missing lemmas
end

| (cif b c₁ c₂) L :=
begin
simp [live, fv_com],
exact sorry -- TODO(dhs): simple
end

| (cwhile b c)  L :=
begin
simp [live, fv_com],
apply fixpoint_upper_bound,
intros start H,
have H_suff : live c start ⊆ fv_com c ∪ L,
exact sorry, -- TODO(dhs): easy
exact sorry -- TODO(dhs): easy
end

lemma live_while_charact (b : bexp) (c : com) (L : list var) :
  let L' := live (cwhile b c) L in
  fv_bexp b ⊆  L' ∧ L ⊆ L' ∧ live c L' ⊆ L' :=
begin
dsimp,
have H := fixpoint_charact (λ xs, fv_bexp b ∪ L ∪ live c xs) (fv_bexp b ∪ fv_com c ∪ L),
cases H with H H,
split,
{ exact sorry },
{ exact sorry },
split,
{ simp [live, fv_com], rw H, apply subset_union_left, apply subset_union_left, apply subset.refl },
split,
{ simp [live, fv_com, H], apply subset_union_right, apply subset.refl  },
{ simp [live, fv_com, H], apply subset_trans, apply live_upper_bound, exact sorry } -- TODO(dhs): easy
end

/- 3. Dead code elimination -/

/- Code transformation -/

/- The code transformation turns assignments [x ::= a] to dead variables [x]
  into [SKIP] statements. -/

def dce : com → list var → com
| cskip         L := cskip
| (cass x e)    L := if x ∈ L then cass x e else cskip
| (cseq c₁ c₂)  L := cseq (dce c₁ (live c₂ L)) (dce c₂ L)
| (cif b c₁ c₂) L := cif b (dce c₁ L) (dce c₂ L)
| (cwhile b c)  L := cwhile b (dce c $ live (cwhile b c) L)

/- Semantic correctness -/

/- Two states agree on a set [L] of live variables if they assign
  the same values to each live variable. -/

def agree (L : list var) (st₁ st₂: vstate) : Prop :=
  ∀ x, x ∈ L → st₁^.dfind x = st₂^.dfind x

/- Monotonicity property. -/

lemma agree_monotonic (L L' : list var) (st₁ st₂ : vstate) :
  agree L' st₁ st₂ → L ⊆ L' → agree L st₁ st₂ :=
begin
simp [agree],
intros H H_ss x H_mem,
simp [H x (H_ss H_mem)]
end

/- Agreement on the free variables of an expression implies that this
    expression evaluates identically in both states. -/

lemma aeval_agree (L : list var) (st₁ st₂ : vstate) (H_agree : agree L st₁ st₂) :
  ∀ (e : aexp), fv_aexp e ⊆ L → aeval st₁ e = aeval st₂ e
| (aexp.aconst n) := λ H_ss, rfl

| (aexp.avar v)   :=
begin
simp [fv_aexp, aeval],
intro H_ss,
apply H_agree,
apply mem_of_subset
end

| (aexp.aadd e₁ e₂) :=
begin
simp [fv_aexp, aeval],
intro H_ss,
have H₁ : aeval st₁ e₁ = aeval st₂ e₁,
{ apply aeval_agree, exact subset_pre_union_left H_ss },
have H₂ : aeval st₁ e₂ = aeval st₂ e₂,
{ apply aeval_agree, exact subset_pre_union_right H_ss },
simp [H₁, H₂]
end

| (aexp.asub e₁ e₂) :=
begin
simp [fv_aexp, aeval],
intro H_ss,
have H₁ : aeval st₁ e₁ = aeval st₂ e₁,
{ apply aeval_agree, exact subset_pre_union_left H_ss },
have H₂ : aeval st₁ e₂ = aeval st₂ e₂,
{ apply aeval_agree, exact subset_pre_union_right H_ss },
simp [H₁, H₂]
end

| (aexp.amul e₁ e₂) :=
begin
simp [fv_aexp, aeval],
intro H_ss,
have H₁ : aeval st₁ e₁ = aeval st₂ e₁,
{ apply aeval_agree, exact subset_pre_union_left H_ss },
have H₂ : aeval st₁ e₂ = aeval st₂ e₂,
{ apply aeval_agree, exact subset_pre_union_right H_ss },
simp [H₁, H₂]
end

set_option pp.all true
set_option trace.simplify true

lemma beval_agree (L : list var) (st₁ st₂ : vstate) (H_agree : agree L st₁ st₂) :
  ∀ (b : bexp), fv_bexp b ⊆ L → beval st₁ b = beval st₂ b
| (bexp.btrue)      H_ss := rfl
| (bexp.bfalse)     H_ss := rfl
| (bexp.bnot b)     H_ss :=
begin
simp [beval], apply congr_arg, apply beval_agree, exact H_ss
end

| (bexp.band b₁ b₂) H_ss :=
begin
simp [fv_bexp] at H_ss,
simp [beval],
have H₁ : beval st₁ b₁ = beval st₂ b₁,
{ apply beval_agree, apply subset_pre_union_left H_ss },
have H₂ : beval st₁ b₂ = beval st₂ b₂,
{ apply beval_agree, apply subset_pre_union_right H_ss },
simp [H₁, H₂]
end

| (bexp.beq e₁ e₂)  H_ss :=
begin
simp [fv_bexp] at H_ss,
simp only [beval],
have H₁ : aeval st₁ e₁ = aeval st₂ e₁,
{ apply aeval_agree, exact H_agree, apply subset_pre_union_left H_ss },
have H₂ : aeval st₁ e₂ = aeval st₂ e₂,
{ apply aeval_agree, exact H_agree, apply subset_pre_union_right H_ss },
-- TODO(dhs): investigate crazy Lean behavior
simp only [H₁]
--rw [H₁, H₂]
end

| (bexp.ble e₁ e₂)  H_ss :=
begin
simp [fv_bexp] at H_ss,
simp [beval],
have H₁ : aeval st₁ e₁ = aeval st₂ e₁,
{ apply aeval_agree, exact H_agree, apply subset_pre_union_left H_ss },
have H₂ : aeval st₁ e₂ = aeval st₂ e₂,
{ apply aeval_agree, exact H_agree, apply subset_pre_union_right H_ss },
-- TODO(dhs): investigate crazy Lean behavior
-- simp only [H₁, H₂]
rw [H₁, H₂]
end

end compiler


/-
Copyright (c) 2022 Antoine Labelle. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Antoine Labelle
-/
import category_theory.monoidal.braided
import category_theory.monoidal.linear
import category_theory.preadditive.additive_functor
import category_theory.linear.linear_functor
import category_theory.closed.monoidal

/-!
# Full monoidal subcategories

Given a monidal category `C` and a monoidal predicate on `C`, that is a function `P : C → Prop`
closed under `𝟙_` and `⊗`, we can put a monoidal structure on `{X : C // P X}` (the category
structure is defined in `category_theory.full_subcategory`).

When `C` is also braided/symmetric, the full monoidal subcategory also inherits the
braided/symmetric structure.

## TODO
* Add monoidal/braided versions of `category_theory.full_subcategory.lift`
-/

universes u v

namespace category_theory

namespace monoidal_category

open iso

variables {C : Type u} [category.{v} C] [monoidal_category C] (P : C → Prop)

/--
A property `C → Prop` is a monoidal predicate if it is closed under `𝟙_` and `⊗`.
-/
class monoidal_predicate : Prop :=
(prop_id' : P (𝟙_ C) . obviously)
(prop_tensor' : ∀ {X Y}, P X → P Y → P (X ⊗ Y) . obviously)

restate_axiom monoidal_predicate.prop_id'
restate_axiom monoidal_predicate.prop_tensor'

open monoidal_predicate

variables [monoidal_predicate P]

/--
When `P` is a monoidal predicate, the full subcategory for `P` inherits the monoidal structure of
  `C`.
-/
instance full_monoidal_subcategory : monoidal_category (full_subcategory P) :=
{ tensor_obj := λ X Y, ⟨X.1 ⊗ Y.1, prop_tensor X.2 Y.2⟩,
  tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, by { change X₁.1 ⊗ X₂.1 ⟶ Y₁.1 ⊗ Y₂.1,
    change X₁.1 ⟶ Y₁.1 at f, change X₂.1 ⟶ Y₂.1 at g, exact f ⊗ g },
  tensor_unit := ⟨𝟙_ C, prop_id⟩,
  associator := λ X Y Z,
    ⟨(α_ X.1 Y.1 Z.1).hom, (α_ X.1 Y.1 Z.1).inv,
     hom_inv_id (α_ X.1 Y.1 Z.1), inv_hom_id (α_ X.1 Y.1 Z.1)⟩,
  left_unitor := λ X, ⟨(λ_ X.1).hom, (λ_ X.1).inv, hom_inv_id (λ_ X.1), inv_hom_id (λ_ X.1)⟩,
  right_unitor := λ X, ⟨(ρ_ X.1).hom, (ρ_ X.1).inv, hom_inv_id (ρ_ X.1), inv_hom_id (ρ_ X.1)⟩,
  tensor_id' := λ X Y, tensor_id X.1 Y.1,
  tensor_comp' := λ X₁ Y₁ Z₁ X₂ Y₂ Z₂ f₁ f₂ g₁ g₂, tensor_comp f₁ f₂ g₁ g₂,
  associator_naturality' := λ X₁ X₂ X₃ Y₁ Y₂ Y₃ f₁ f₂ f₃, associator_naturality f₁ f₂ f₃,
  left_unitor_naturality' := λ X Y f, left_unitor_naturality f,
  right_unitor_naturality' := λ X Y f, right_unitor_naturality f,
  pentagon' := λ W X Y Z, pentagon W.1 X.1 Y.1 Z.1,
  triangle' := λ X Y, triangle X.1 Y.1 }

/--
The forgetful monoidal functor from a full monoidal subcategory into the original category
("forgetting" the condition).
-/
@[simps]
def full_monoidal_subcategory_inclusion : monoidal_functor (full_subcategory P) C :=
{ to_functor := full_subcategory_inclusion P,
  ε := 𝟙 _,
  μ := λ X Y, 𝟙 _ }

instance full_monoidal_subcategory.full :
  full (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.full P
instance full_monoidal_subcategory.faithful :
  faithful (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.faithful P

section

variables [preadditive C]

instance full_monoidal_subcategory_inclusion_additive :
  (full_monoidal_subcategory_inclusion P).to_functor.additive :=
functor.full_subcategory_inclusion_additive _

instance [monoidal_preadditive C] : monoidal_preadditive (full_subcategory P) :=
monoidal_preadditive_of_faithful (full_monoidal_subcategory_inclusion P)

variables (R : Type*) [ring R] [linear R C]

instance full_monoidal_subcategory_inclusion_linear :
  (full_monoidal_subcategory_inclusion P).to_functor.linear R :=
functor.full_subcategory_inclusion_linear R _

instance [monoidal_preadditive C] [monoidal_linear R C] : monoidal_linear R (full_subcategory P) :=
monoidal_linear_of_faithful R (full_monoidal_subcategory_inclusion P)

end

variables {P} {P' : C → Prop} [monoidal_predicate P']

/-- An implication of predicates `P → P'` induces a monoidal functor between full monoidal
subcategories. -/
@[simps]
def full_monoidal_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) :
  monoidal_functor (full_subcategory P) (full_subcategory P')  :=
{ to_functor := full_subcategory.map h,
  ε := 𝟙 _,
  μ := λ X Y, 𝟙 _ }

instance full_monoidal_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) :
  full (full_monoidal_subcategory.map h).to_functor := { preimage := λ X Y f, f }
instance full_monoidal_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) :
  faithful (full_monoidal_subcategory.map h).to_functor := {}

section braided

variables (P) [braided_category C]

/--
The braided structure on a full subcategory inherited by the braided structure on `C`.
-/
instance full_braided_subcategory : braided_category (full_subcategory P) :=
braided_category_of_faithful (full_monoidal_subcategory_inclusion P)
  (λ X Y, ⟨(β_ X.1 Y.1).hom, (β_ X.1 Y.1).inv, (β_ X.1 Y.1).hom_inv_id, (β_ X.1 Y.1).inv_hom_id⟩)
  (λ X Y, by tidy)

/--
The forgetful braided functor from a full braided subcategory into the original category
("forgetting" the condition).
-/
@[simps]
def full_braided_subcategory_inclusion : braided_functor (full_subcategory P) C :=
{ to_monoidal_functor := full_monoidal_subcategory_inclusion P,
  braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy } }

instance full_braided_subcategory.full :
  full (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.full P
instance full_braided_subcategory.faithful :
  faithful (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.faithful P

variables {P}

/-- An implication of predicates `P → P'` induces a braided functor between full braided
subcategories. -/
@[simps]
def full_braided_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) :
  braided_functor (full_subcategory P) (full_subcategory P')  :=
{ to_monoidal_functor := full_monoidal_subcategory.map h,
  braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy }  }

instance full_braided_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) :
  full (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_full h
instance full_braided_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) :
  faithful (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_faithful h

end braided

section symmetric

variables (P) [symmetric_category C]

instance full_symmetric_subcategory : symmetric_category (full_subcategory P) :=
symmetric_category_of_faithful (full_braided_subcategory_inclusion P)

end symmetric

section closed

variables (P) [monoidal_closed C]

/--
A property `C → Prop` is a closed predicate if it is closed under taking internal homs
-/
class closed_predicate : Prop :=
(prop_ihom' : ∀ {X Y}, P X → P Y → P ((ihom X).obj Y) . obviously)

restate_axiom closed_predicate.prop_ihom'

open closed_predicate

variable  [closed_predicate P]

instance full_monoidal_closed_subcategory : monoidal_closed (full_subcategory P) :=
{ closed' := λ X,
  { is_adj :=
    { right := full_subcategory.lift P (full_subcategory_inclusion P ⋙ (ihom X.1))
        (λ Y, prop_ihom X.2 Y.2),
      adj := adjunction.mk_of_unit_counit
      { unit := { app := λ Y, (ihom.coev X.1).app Y.1,
                  naturality' := λ Y Z f, ihom.coev_naturality X.1 f },
        counit := { app := λ Y, (ihom.ev X.1).app Y.1,
                    naturality' := λ Y Z f, ihom.ev_naturality X.1 f },
        left_triangle' := by { ext Y, simp, exact ihom.ev_coev X.1 Y.1 },
        right_triangle' := by { ext Y, simp, exact ihom.coev_ev X.1 Y.1 } } } } }

@[simp] lemma full_monoidal_closed_subcategory_ihom_obj (X Y : full_subcategory P) :
  ((ihom X).obj Y).obj = (ihom (X.obj)).obj Y.obj := rfl

@[simp] lemma full_monoidal_closed_subcategory_ihom_map (X : full_subcategory P)
  {Y Z : full_subcategory P}
  (f : Y ⟶ Z) : (ihom X).map f = (ihom (X.obj)).map f := rfl

end closed

end monoidal_category

end category_theory


import for_mathlib.derived.example
import for_mathlib.derived.les3

.

noncomputable theory

universes v u

open category_theory category_theory.limits category_theory.triangulated homotopy_category opposite
open bounded_homotopy_category

variables {C : Type u} [category.{v} C] [abelian C] [enough_projectives C]

-- move me
instance is_bounded_above_shift {A : cochain_complex C ℤ} [is_bounded_above ⟨A⟩] (i : ℤ) :
  is_bounded_above {as := A⟦i⟧} :=
begin
  obtain ⟨a, ha⟩ := is_bounded_above.cond ⟨A⟩,
  refine ⟨⟨a - i, _⟩⟩,
  intros j hj,
  rw sub_le_iff_le_add at hj,
  exact ha (j + i) hj,
end

section

-- move me
instance homological_complex.single_additive (i : ℤ) :
  (homological_complex.single C (complex_shape.up ℤ) i).additive :=
{ map_add' := λ X Y f g, begin
    ext n, dsimp, by_cases hn : n = i,
    { subst n, rw [dif_pos rfl, dif_pos rfl, dif_pos rfl],
      simp only [preadditive.add_comp, preadditive.comp_add], },
    { rw [dif_neg hn, dif_neg hn, dif_neg hn, add_zero], },
  end }

-- move me
instance bounded_homotopy_category.single_additive (i : ℤ) :
  (bounded_homotopy_category.single C i).additive :=
{ map_add' := λ X Y f g, begin
    delta bounded_homotopy_category.single,
    dsimp,
    rw functor.map_add,
    refl
  end }

instance Ext.additive (i : ℤ) :
  (Ext i : (bounded_homotopy_category C)ᵒᵖ ⥤ bounded_homotopy_category C ⥤ Ab).additive :=
{ map_add' := λ X Y f g, begin
    ext B e,
    dsimp [Ext],
    rw [preadditive.comp_add, lift_add, preadditive.add_comp],
  end }

-- move me
instance Ext'.flip_additive (i : ℤ) (B : C) : ((Ext' i).flip.obj B).additive :=
{ map_add' := λ X Y f g,
  begin
    delta Ext',
    dsimp,
    rw [functor.map_add, op_add, functor.map_add],
    refl,
  end }

-- move me
instance Ext'.additive (i : ℤ) (A : Cᵒᵖ) : ((Ext' i).obj A).additive :=
{ map_add' := λ X Y f g,
  begin
    delta Ext',
    dsimp,
    rw [functor.map_add, functor.map_add],
  end }

end

lemma is_zero_iff_epi_and_is_iso
  {A₁ A₂ A₃ : C} (f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) (B : C) (h : short_exact f g) :
  (∀ i > 0, is_zero (((Ext' i).obj (op A₃)).obj B)) ↔
  (epi (((Ext' 0).map f.op).app B) ∧ ∀ i > 0, is_iso (((Ext' i).map f.op).app B)) :=
begin
  have LES := λ i, h.Ext'_five_term_exact_seq B i,
  split,
  { intro H,
    split,
    { have := ((LES 0).drop 1).pair,
      refine this.epi_iff_eq_zero.mpr _,
      refine is_zero.eq_of_tgt _ _ _,
      exact H 1 zero_lt_one, },
    { rintro i (hi : 0 < i),
      apply (LES i).is_iso_of_zero_of_zero,
      { refine is_zero.eq_of_src _ _ _,
        exact H i hi, },
      { refine is_zero.eq_of_tgt _ _ _,
        exact H (i+1) (hi.trans $ lt_add_one _), }, } },
  { intros H i hi,
    obtain ⟨i, rfl⟩ : ∃ j, j + 1 = i := ⟨i-1, sub_add_cancel _ _⟩,
    refine is_zero_of_exact_zero_zero' _ _ ((LES i).drop 2).pair _ _,
    { refine ((LES i).drop 1).pair.epi_iff_eq_zero.mp _,
      rw [gt_iff_lt, int.lt_add_one_iff] at hi,
      obtain (rfl|hi) := hi.eq_or_lt,
      { exact H.1 },
      { exact @is_iso.epi_of_iso _ _ _ _ _ (H.2 _ hi), } },
    { refine (LES (i+1)).pair.mono_iff_eq_zero.mp _,
      exact @is_iso.mono_of_iso _ _ _ _ _ (H.2 _ hi), } }
end

lemma epi_and_is_iso_iff_of_is_iso
  {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C}
  (f₁ : X₁ ⟶ X₂) (f₂ : X₂ ⟶ X₃)
  (g₁ : Y₁ ⟶ Y₂) (g₂ : Y₂ ⟶ Y₃)
  (α₁ : X₁ ⟶ Y₁) (α₂ : X₂ ⟶ Y₂) (α₃ : X₃ ⟶ Y₃)
  (sq₁ : f₁ ≫ α₂ = α₁ ≫ g₁) (sq₂ : f₂ ≫ α₃ = α₂ ≫ g₂)
  (Z : C) (hf : short_exact f₁ f₂) (hg : short_exact g₁ g₂)
  (H : ∀ i, is_iso (((Ext' i).map α₃.op).app Z)) :
  (epi (((Ext' 0).map α₁.op).app Z) ∧ ∀ i > 0, is_iso (((Ext' i).map α₁.op).app Z)) ↔
  (epi (((Ext' 0).map α₂.op).app Z) ∧ ∀ i > 0, is_iso (((Ext' i).map α₂.op).app Z)) :=
begin
  let E : ℤ → Cᵒᵖ ⥤ Ab := λ n, (Ext' n).flip.obj Z,
  have H1 := λ i, hf.Ext'_five_term_exact_seq Z i,
  have H2 := λ i, hg.Ext'_five_term_exact_seq Z i,
  have sq1 : ∀ i, (E i).map α₃.op ≫ (E i).map f₂.op = (E i).map g₂.op ≫ (E i).map α₂.op,
  { intro, simp only [← (E i).map_comp, ← op_comp, sq₂], },
  have sq2 : ∀ i, (E i).map α₂.op ≫ (E i).map f₁.op = (E i).map g₁.op ≫ (E i).map α₁.op,
  { intro, simp only [← (E i).map_comp, ← op_comp, sq₁], },
  have sq3 : ∀ i, (E i).map α₁.op ≫ Ext'_δ Z hf i = Ext'_δ Z hg i ≫ (E (i+1)).map α₃.op,
  { apply Ext'_δ_natural f₁ f₂ g₁ g₂ α₁ α₂ α₃ sq₁ sq₂ Z hf hg, },
  split; rintro ⟨h1, h2⟩,
  { split,
    { show epi (((E 0).map α₂.op)),
      refine abelian.epi_of_epi_of_epi_of_mono (sq1 0) (sq2 0) (sq3 0)
        ((H2 0).drop 1).pair ((H1 0).drop 0).pair ((H1 0).drop 1).pair _ h1 _,
      { exact @is_iso.epi_of_iso _ _ _ _ _ (H 0), },
      { exact @is_iso.mono_of_iso _ _ _ _ _ (H 1), } },
    { rintros i (hi : 0 < i),
      suffices : mono ((E i).map α₂.op) ∧ epi ((E i).map α₂.op),
      { cases this with aux1 aux2, refine @is_iso_of_mono_of_epi _ _ _ _ _ _ aux1 aux2 },
      split,
      { obtain ⟨i, rfl⟩ : ∃ j, j+1 = i := ⟨i-1, sub_add_cancel _ _⟩,
        refine abelian.mono_of_epi_of_mono_of_mono (sq3 i) (sq1 (i+1)) (sq2 (i+1))
          ((H2 i).drop 2).pair ((H2 (i+1)).drop 0).pair ((H1 i).drop 2).pair _ _ _,
        { obtain (rfl|hi') := eq_or_ne i 0,
          { apply h1 },
          { refine @is_iso.epi_of_iso _ _ _ _ _ (h2 _ _),
            rw int.lt_add_one_iff at hi, refine lt_of_le_of_ne hi hi'.symm, } },
        { exact @is_iso.mono_of_iso _ _ _ _ _ (H _), },
        { exact @is_iso.mono_of_iso _ _ _ _ _ (h2 _ hi), } },
      { refine abelian.epi_of_epi_of_epi_of_mono (sq1 i) (sq2 i) (sq3 i)
          ((H2 i).drop 1).pair ((H1 i).drop 0).pair ((H1 i).drop 1).pair _ _ _,
        { exact @is_iso.epi_of_iso _ _ _ _ _ (H _), },
        { exact @is_iso.epi_of_iso _ _ _ _ _ (h2 _ hi), },
        { exact @is_iso.mono_of_iso _ _ _ _ _ (H _), } } } },
  { split,
    { refine abelian.epi_of_epi_of_epi_of_mono (sq2 0) (sq3 0) (sq1 1)
        ((H2 0).drop 2).pair ((H1 0).drop 1).pair ((H1 0).drop 2).pair h1 _ _,
      { exact @is_iso.epi_of_iso _ _ _ _ _ (H 1), },
      { exact @is_iso.mono_of_iso _ _ _ _ _ (h2 _ zero_lt_one), } },
    { intros i hi,
      refine abelian.is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso'
        (sq1 i) (sq2 i) (sq3 i) (sq1 (i+1))
        (H2 i).pair ((H2 i).drop 1).pair ((H2 i).drop 2).pair
        (H1 i).pair ((H1 i).drop 1).pair ((H1 i).drop 2).pair
        (H _) (h2 _ hi) (H _) (h2 _ (add_pos hi zero_lt_one)), } }
end