/-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import data.padics.padic_integers
import topology.metric_space.cau_seq_filter
import analysis.specific_limits
import data.polynomial.identities
import topology.algebra.polynomial

/-!
# Hensel's lemma on ℤ_p

This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup:
<http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>

Hensel's lemma gives a simple condition for the existence of a root of a polynomial.

The proof and motivation are described in the paper
[R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019].

## References

* <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/Hensel%27s_lemma>

## Tags

p-adic, p adic, padic, p-adic integer
-/

noncomputable theory

open_locale classical topological_space

-- We begin with some general lemmas that are used below in the computation.

lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) :
  ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ :=
let ⟨z, hz⟩ := F.eval_sub_factor x y in calc
  ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz]
    ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _)
    ... = ∥x - y∥ : by simp

open filter metric

private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]}
  (ncs : cau_seq ℤ_[p] norm) :
  tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) :=
F.continuous_at.tendsto.comp ncs.tendsto_limit

section
parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]}
           (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥)
include ncs_der_val

private lemma ncs_tendsto_const :
  tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) :=
by convert tendsto_const_nhds; ext; rw ncs_der_val

private lemma ncs_tendsto_lim :
  tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) :=
tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _)

private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ :=
tendsto_nhds_unique ncs_tendsto_lim ncs_tendsto_const

end

section
parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]}
           (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0))
include hnorm

private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) :=
tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm)

lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 :=
tendsto_nhds_unique (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero

end

section hensel
open nat

parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]}
           (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0)
include hnorm

/-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/
private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥

private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 :=
lt_of_le_of_lt (norm_nonneg _) hnorm

private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos

private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 :=
λ h, deriv_sq_norm_ne_zero (by simp [*, sq])

private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ :=
lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero)

private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero

private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 :=
calc T = ∥F.eval a∥ / ∥((F.derivative.eval a)^2 : ℚ_[p])∥ : normed_field.norm_div _ _
   ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_int.norm_def]
   ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp

private lemma T_lt_one : T < 1 :=
let h := (div_lt_one deriv_sq_norm_pos).2 hnorm in
by rw T_def; apply h

private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 :=
have T ^ n ≤ T ^ 1,
from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn),
lt_of_le_of_lt (by simpa) T_lt_one

private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (pow_pos (by norm_num) _))

private lemma T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg (norm_nonneg _) _

/-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/
private def ih (n : ℕ) (z : ℤ_[p]) : Prop :=
∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n)

private lemma ih_0 : ih 0 a :=
⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩

private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) :
         ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 :=
calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥
    = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _
... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1]
... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ :
  (div_le_div_right deriv_norm_pos).2 hz.2
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _
... ≤ 1 : mul_le_one (padic_int.norm_le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _))

private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1)
  (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) :
  ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ :=
calc
  ∥F.derivative.eval z' - F.derivative.eval z∥
    ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _
... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg]
... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1
... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ :
  (div_le_div_right deriv_norm_pos).2 hz.2
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _
... < ∥F.derivative.eval a∥ :
  (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _))

private def calc_eval_z'  {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z)
  (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) :
  {q : ℤ_[p] // F.eval z' = q * z1^2} :=
have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from
  have hdzne : F.derivative.eval z ≠ 0,
    from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption),
  λ h, hdzne $ subtype.ext_iff_val.2 h,
let ⟨q, hq⟩ := F.binom_expansion z (-z1) in
have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1,
  by { rw padic_norm_e.mul, exact mul_le_one (padic_int.norm_le_one _) (norm_nonneg _) h1 },
have F.derivative.eval z * (-z1) = -F.eval z, from calc
  F.derivative.eval z * (-z1)
    = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq]
... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) :
  by simp [subtype.ext_iff_val]
... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) :
  subtype.ext $ by simp
... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'],
have heq : F.eval z' = q * z1^2, by simpa [sub_eq_add_neg, this, hz'] using hq,
⟨q, heq⟩

private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q}
  (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1)
  (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) :=
calc ∥F.eval z'∥
    = ∥q∥ * ∥z1∥^2 : by simp [heq]
... ≤ 1 * ∥z1∥^2 :
  mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (pow_nonneg (norm_nonneg _) _)
... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 :
  by simp [hzeq, hz.1, div_pow]
... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 :
  (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _)
... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [mul_pow]
... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _
... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul, pow_succ' 2]

set_option eqn_compiler.zeta true

/-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need
the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/
private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} :=
have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz,
let z1 : ℤ_[p] := ⟨_, h1⟩,
    z' : ℤ_[p] := z - z1 in
⟨ z',
  have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥,
    from calc_deriv_dist rfl (by simp [z1, hz.1]) hz,
  have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥,
    begin
      rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist,
      have := padic_int.norm_eq_of_norm_add_lt_right hdist,
      rwa [norm_neg, hz.1] at this
    end,
  let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in
  have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)),
    from calc_eval_z'_norm hz heq h1 rfl,
  ⟨hfeq, hnle⟩⟩

set_option eqn_compiler.zeta false

-- why doesn't "noncomputable theory" stick here?
private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z}
| 0 := ⟨a, ih_0⟩
| (k+1) := ih_n (newton_seq_aux k).2

private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1

private lemma newton_seq_deriv_norm (n : ℕ) :
  ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ :=
(newton_seq_aux n).2.1

private lemma newton_seq_norm_le (n : ℕ) :
  ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) :=
(newton_seq_aux n).2.2

private lemma newton_seq_norm_eq (n : ℕ) :
  ∥newton_seq (n+1) - newton_seq n∥ =
    ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ :=
by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm]

private lemma newton_seq_succ_dist (n : ℕ) :
  ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) :=
calc ∥newton_seq (n+1) - newton_seq n∥
    = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _
... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm
... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ :
  (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _)
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _

include hnsol
private lemma T_pos : T > 0 :=
begin
  rw T_def,
  exact div_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm)
end

private lemma newton_seq_succ_dist_weak (n : ℕ) :
  ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ :=
have 2 ≤ 2^(n+1),
  from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1),
    by simpa using this,
calc ∥newton_seq (n+2) - newton_seq (n+1)∥
    ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _
... ≤ ∥F.derivative.eval a∥ * T^2 :
  mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this)
    (norm_nonneg _)
... < ∥F.derivative.eval a∥ * T^1 :
  mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos
... = ∥F.eval a∥ / ∥F.derivative.eval a∥ :
  begin
    rw [T, sq, pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul],
    apply mul_div_mul_left,
    apply deriv_norm_ne_zero; assumption
  end

private lemma newton_seq_dist_aux (n : ℕ) :
  ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n)
| 0 := by simp [T_pow_nonneg hnorm, mul_nonneg]
| (k+1) :=
  have 2^n ≤ 2^(n+k),
    by {apply pow_le_pow, norm_num, apply nat.le_add_right},
  calc
  ∥newton_seq (n + (k + 1)) - newton_seq n∥
    = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc
... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ :
  by rw ←sub_add_sub_cancel
... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) :
  padic_int.nonarchimedean _ _
... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) :
  max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _)
... = ∥F.derivative.eval a∥ * T^(2^n) :
  max_eq_right $ mul_le_mul_of_nonneg_left
    (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _)

private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) :
  ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) :=
have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk,
let ⟨_, hex'⟩ := hex in
by rw hex'; apply newton_seq_dist_aux; assumption

private lemma newton_seq_dist_to_a :
  ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥
| 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n]
| (k+2) h :=
  have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥,
    by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption,
  have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt,
  calc  ∥newton_seq (k + 2) - a∥
    = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel
... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) :
  padic_int.norm_add_eq_max_of_ne hne'
... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt
... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ :
  newton_seq_dist_to_a (k+1) (succ_pos _)

private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) :=
begin
  rw ←mul_zero (∥F.derivative.eval a∥),
  exact tendsto_const_nhds.mul
                    (tendsto.comp
                      (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm))
                      (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num)))
end

private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε :=
have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0,
  from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _),
begin
  have := bound' hnorm hnsol,
  simp [tendsto, nhds] at this,
  intros ε hε,
  cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN,
  existsi N, intros n hn,
  simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn
end

private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) :=
begin
  rw [←mul_zero (∥F.derivative.eval a∥), sq],
  simp only [mul_assoc],
  apply tendsto.mul,
  { apply tendsto_const_nhds },
  { apply bound', assumption }
end

private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq :=
begin
  intros ε hε,
  cases bound hnorm hnsol hε with N hN,
  existsi N,
  intros j hj,
  apply lt_of_le_of_lt,
  { apply newton_seq_dist _ _ hj, assumption },
  { apply hN, apply le_refl }
end

private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩

private def soln : ℤ_[p] := newton_cau_seq.lim

private lemma soln_spec {ε : ℝ} (hε : ε > 0) :
  ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε :=
setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε

private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ :=
norm_deriv_eq newton_seq_deriv_norm

private lemma newton_seq_norm_tendsto_zero :
  tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) :=
squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq

private lemma newton_seq_dist_tendsto :
  tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) :=
tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩

private lemma newton_seq_dist_tendsto' :
  tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) :=
(continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds)

private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ :=
tendsto_nhds_unique newton_seq_dist_tendsto' newton_seq_dist_tendsto

private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ :=
begin
  rw [soln_dist_to_a, div_lt_iff],
  { rwa sq at hnorm },
  { apply deriv_norm_pos, assumption }
end

private lemma eval_soln : F.eval soln = 0 :=
limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero

private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0)
  (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) :
  z = soln :=
have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc
  ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel
        ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_int.nonarchimedean _ _
        ... < ∥F.derivative.eval a∥ : max_lt hnlt (norm_sub_rev soln a ▸ soln_dist_to_a_lt_deriv),
let h := z - soln,
    ⟨q, hq⟩ := F.binom_expansion soln h in
have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc
  0 = F.eval (soln + h) : by simp [hev, h]
... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add]
... = (F.derivative.eval soln + q * h) * h : by rw [sq, right_distrib, mul_assoc]),
have h = 0, from by_contradiction $ λ hne,
  have F.derivative.eval soln + q * h = 0,
    from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne,
  have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this,
  lt_irrefl ∥F.derivative.eval soln∥ (calc
  ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this
... ≤ 1 * ∥h∥ :
  by { rw padic_int.norm_mul,
       exact mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) }
... = ∥z - soln∥ : by simp [h]
... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist),
eq_of_sub_eq_zero (by rw ←this; refl)

end hensel

variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]}

private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0)
  (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a :=
let h := z' - a,
    ⟨q, hq⟩ := F.binom_expansion a h in
have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc
  0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz']
... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add]
... = (F.derivative.eval a + q * h) * h : by rw [sq, right_distrib, mul_assoc]),
have h = 0, from by_contradiction $ λ hne,
  have F.derivative.eval a + q * h = 0,
    from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne,
  have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this,
  lt_irrefl ∥F.derivative.eval a∥ (calc
    ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this]
    ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _)
    ... < ∥F.derivative.eval a∥ : by simpa [h]),
eq_of_sub_eq_zero (by rw ←this; refl)

variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2)
include hnorm

private lemma a_is_soln (ha : F.eval a = 0) :
  F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧
  ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a :=
⟨ha, by simp [deriv_ne_zero hnorm], rfl, a_soln_is_unique ha⟩

lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧
  ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧
  ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z :=
if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else
by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _,
  soln_unique _ _⟩; assumption


constant f : Nat → Nat
@[simp] axiom fEq (x : Nat) (h : x ≠ 0) : f x = x

example (x : Nat) (h : x ≠ 0) : f x = x + 0 := by
  simp (discharger := trace_state; exact (fun h' => h') h)

example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by
  simp (discharger := trace_state; assumption)
  assumption

example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by
  simp (discharger := assumption)
  assumption

example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by
  simp (disch := assumption)
  assumption

example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by
  conv => lhs; simp (disch := assumption)
  trace_state
  conv => rhs; simp (disch := assumption)
  trace_state
  assumption


import topology.basic
import data.real.basic
import topology.metric_space.basic
import topology.uniform_space.uniform_convergence
import topology.uniform_space.basic

-- set_option pp.all true

open filter

theorem unif_cont
  (F : ℕ → ℝ → ℝ) (hF : ∀ n, continuous (F n))
  (f : ℝ → ℝ) (hFf : tendsto_uniformly F f at_top) :
  continuous f :=
begin
  -- set up fully "peeled" proof state:
  rw metric.continuous_iff,    -- metric def of continuity
  intros x ε hε,    -- introduce universally quantified variables into the proof state

  -- solution to disallowed metavarible dependencies: skolimize and rcases first!
  simp [metric.continuous_iff] at hF,    -- metric definition of continuity
  simp [classical.skolem] at hF,
  -- sometimes with skolem behind other universal quantifiers, you need to help Lean a bit
  -- (simp and rw don't work)
  -- rw [classical.skolem] at hF,    -- try yourself
  -- simp [classical.skolem] at hF,  -- try yourself
  have hF := λ n b, classical.skolem.mp (hF n b),
  have hF' := λ n, classical.skolem.mp (hF n),
  simp [classical.skolem] at hF',
  clear hF,
  clear hF,
  rcases hF' with ⟨δ, hF⟩,
  have hδ := λ n x ε hε, and.elim_left (hF n x ε hε),
  have hF := λ n x ε hε, and.elim_right (hF n x ε hε),

  -- the same for the other hypothesis
  rw metric.tendsto_uniformly_iff at hFf,
  simp at hFf,    -- get rid of `at_top`
  simp [classical.skolem] at hFf,
  rcases hFf with ⟨M, hM⟩,

  apply exists.intro,    -- delay choice, creates mvars
  apply exists.intro,    -- delay choice, creates mvars
  rotate 1,    -- postpone a goal by rotating the goal list
  intros y hxy,

  -- start the proof
  apply lt_of_le_of_lt,    -- transitivity
  apply dist_triangle,     -- triangle inequality
  rotate 1,
  apply lt_of_lt_of_le,
  apply add_lt_add_left,    -- bound a summand
  rw dist_comm,    -- symmetry
  apply hM,    -- apply the hypothesis

  rotate 4,
  apply le_trans,
  apply add_le_of_add_le_right,
  rotate 1,
  apply dist_triangle,
  rotate 9,
  -- apply le_trans,
  apply add_le_of_add_le_right,
  rotate 1,
  apply add_le_of_add_le_right,
  rotate 1,
  apply le_of_lt,
  apply hM,
  rotate 14,
  apply add_le_of_add_le_left,
  rotate 1,
  have hF' := hF _,    -- apply the hypothesis to an argument to be specified later
  apply le_of_lt,
  apply hF',

  -- supply all the epsilons
  rotate 2,
  use ε / 3,
  apply le_refl,
  rotate 1,
  use ε / 3,
  rotate 2,
  rotate 1,
  -- use ε,
  use δ (M (ε / 3) (by linarith)) x (ε / 3) (by linarith),  -- now we can supply "the" delta belonging to "the" M
  rotate 1,
  apply le_refl,
  apply le_of_eq,
  apply add_eq_of_eq_sub,
  refl,
  apply le_of_eq,
  apply eq_sub_of_add_eq,
  ring_nf,
  exact hxy,
  apply le_refl,
  apply hδ,
end

-- Toy example for this sort of behavior:
-- if we defer the choice of `y` at the very beginning,
-- the goal cannot be closed with `hx`
-- because it would assign `x` to the second goal which (syntactically) is not allowed.
-- But above we **need** to delay the choice of `δ` early so that we can continue to unpack and work with the goal.
theorem test (h : ∃ x, x = 0) : ∃ y, y = 0 :=
begin
  -- apply exists.intro,    -- uncomment
  rcases h with ⟨x, hx⟩,
  apply exists.intro,    -- comment
  exact hx,
end


/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Haitao Zhang
-/
prelude
import init.data.prod init.funext init.logic
/-!
# General operations on functions
-/
universes u₁ u₂ u₃ u₄

namespace function
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}

/-- Composition of functions: `(f ∘ g) x = f (g x)`. -/
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
λ x, f (g x)

/-- Composition of dependent functions: `(f ∘' g) x = f (g x)`, where type of `g x` depends on `x`
and type of `f (g x)` depends on `x` and `g x`. -/
@[inline, reducible] def dcomp {β : α → Sort u₂} {φ : Π {x : α}, β x → Sort u₃}
  (f : Π {x : α} (y : β x), φ y) (g : Π x, β x) : Π x, φ (g x) :=
λ x, f (g x)

infixr ` ∘ `:90  := function.comp
infixr ` ∘' `:80 := function.dcomp

@[reducible] def comp_right (f : β → β → β) (g : α → β) : β → α → β :=
λ b a, f b (g a)

@[reducible] def comp_left (f : β → β → β) (g : α → β) : α → β → β :=
λ a b, f (g a) b

/-- Given functions `f : β → β → φ` and `g : α → β`, produce a function `α → α → φ` that evaluates
`g` on each argument, then applies `f` to the results. Can be used, e.g., to transfer a relation
from `β` to `α`. -/
@[reducible] def on_fun (f : β → β → φ) (g : α → β) : α → α → φ :=
λ x y, f (g x) (g y)

@[reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
  : α → β → ζ :=
λ x y, op (f x y) (g x y)

/-- Constant `λ _, a`. -/
@[reducible] def const (β : Sort u₂) (a : α) : β → α :=
λ x, a

@[reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y :=
λ y x, f x y

@[reducible] def app {β : α → Sort u₂} (f : Π x, β x) (x : α) : β x :=
f x

infixl  ` on `:2         := on_fun
notation f ` -[` op `]- ` g  := combine f op g

lemma left_id (f : α → β) : id ∘ f = f := rfl

lemma right_id (f : α → β) : f ∘ id = f := rfl

@[simp] lemma comp_app (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl

lemma comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ (g ∘ h) := rfl

@[simp] lemma comp.left_id (f : α → β) : id ∘ f = f := rfl

@[simp] lemma comp.right_id (f : α → β) : f ∘ id = f := rfl

lemma comp_const_right (f : β → φ) (b : β) : f ∘ (const α b) = const α (f b) := rfl

/-- A function `f : α → β` is called injective if `f x = f y` implies `x = y`. -/
def injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂

lemma injective.comp {g : β → φ} {f : α → β} (hg : injective g) (hf : injective f) :
  injective (g ∘ f) :=
assume a₁ a₂, assume h, hf (hg h)

/-- A function `f : α → β` is called surjective if every `b : β` is equal to `f a`
for some `a : α`. -/
@[reducible] def surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b

lemma surjective.comp {g : β → φ} {f : α → β} (hg : surjective g) (hf : surjective f) :
  surjective (g ∘ f) :=
λ (c : φ), exists.elim (hg c) (λ b hb, exists.elim (hf b) (λ a ha,
  exists.intro a (show g (f a) = c, from (eq.trans (congr_arg g ha) hb))))

/-- A function is called bijective if it is both injective and surjective. -/
def bijective (f : α → β) := injective f ∧ surjective f

lemma bijective.comp {g : β → φ} {f : α → β} : bijective g → bijective f → bijective (g ∘ f)
| ⟨h_ginj, h_gsurj⟩ ⟨h_finj, h_fsurj⟩ := ⟨h_ginj.comp h_finj, h_gsurj.comp h_fsurj⟩

/-- `left_inverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/
def left_inverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x

/-- `has_left_inverse f` means that `f` has an unspecified left inverse. -/
def has_left_inverse (f : α → β) : Prop := ∃ finv : β → α, left_inverse finv f

/-- `right_inverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/
def right_inverse (g : β → α) (f : α → β) : Prop := left_inverse f g

/-- `has_right_inverse f` means that `f` has an unspecified right inverse. -/
def has_right_inverse (f : α → β) : Prop := ∃ finv : β → α, right_inverse finv f

lemma left_inverse.injective {g : β → α} {f : α → β} : left_inverse g f → injective f :=
assume h a b faeqfb,
calc a = g (f a) : (h a).symm
... = g (f b) : congr_arg g faeqfb
... = b : h b

lemma has_left_inverse.injective {f : α → β} : has_left_inverse f → injective f :=
assume h, exists.elim h (λ finv inv, inv.injective)

lemma right_inverse_of_injective_of_left_inverse {f : α → β} {g : β → α}
    (injf : injective f) (lfg : left_inverse f g) :
  right_inverse f g :=
assume x,
have h : f (g (f x)) = f x, from lfg (f x),
injf h

lemma has_right_inverse.surjective {f : α → β} : has_right_inverse f → surjective f
| ⟨finv, inv⟩ := inv.surjective

lemma left_inverse_of_surjective_of_right_inverse {f : α → β} {g : β → α}
    (surjf : surjective f) (rfg : right_inverse f g) :
  left_inverse f g :=
assume y, exists.elim (surjf y) (λ x hx, calc
  f (g y) = f (g (f x)) : hx ▸ rfl
      ... = f x         : eq.symm (rfg x) ▸ rfl
      ... = y           : hx)

lemma injective_id : injective (@id α) := assume a₁ a₂ h, h

lemma surjective_id : surjective (@id α) := assume a, ⟨a, rfl⟩

lemma bijective_id : bijective (@id α) := ⟨injective_id, surjective_id⟩

end function

namespace function
variables {α : Type u₁} {β : Type u₂} {φ : Type u₃}

/-- Interpret a function on `α × β` as a function with two arguments. -/
@[inline] def curry : (α × β → φ) → α → β → φ :=
λ f a b, f (a, b)

/-- Interpret a function with two arguments as a function on `α × β` -/
@[inline] def uncurry : (α → β → φ) → α × β → φ :=
λ f a, f a.1 a.2

@[simp] lemma curry_uncurry (f : α → β → φ) : curry (uncurry f) = f :=
rfl

@[simp] lemma uncurry_curry (f : α × β → φ) : uncurry (curry f) = f :=
funext (λ ⟨a, b⟩, rfl)

protected lemma left_inverse.id {g : β → α} {f : α → β} (h : left_inverse g f) : g ∘ f = id :=
funext h

protected lemma right_inverse.id {g : β → α} {f : α → β} (h : right_inverse g f) : f ∘ g = id :=
funext h

end function


/-
Copyright (c) 2022 Yaël Dillies, Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Junyan Xu

! This file was ported from Lean 3 source module order.extension.well
! leanprover-community/mathlib commit 23aa88e32dcc9d2a24cca7bc23268567ed4cd7d6
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Prod.Lex
import Mathbin.SetTheory.Ordinal.Arithmetic

/-!
# Extend a well-founded order to a well-order

> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.

This file constructs a well-order (linear well-founded order) which is an extension of a given
well-founded order.

## Proof idea

We can map our order into two well-orders:
* the first map respects the order but isn't necessarily injective. Namely, this is the *rank*
  function `rank : α → ordinal`.
* the second map is injective but doesn't necessarily respect the order. This is an arbitrary
  well-order on `α`.

Then their lexicographic product is a well-founded linear order which our original order injects in.
-/

universe u

variable {α : Type u} {r : α → α → Prop}

namespace WellFounded

variable (hwf : WellFounded r)

include hwf

#print WellFounded.wellOrderExtension /-
/-- An arbitrary well order on `α` that extends `r`.

The construction maps `r` into two well-orders: the first map is `well_founded.rank`, which is not
necessarily injective but respects the order `r`; the other map is the identity (with an arbitrarily
chosen well-order on `α`), which is injective but doesn't respect `r`.

By taking the lexicographic product of the two, we get both properties, so we can pull it back and
get an well-order that extend our original order `r`. Another way to view this is that we choose an
arbitrary well-order to serve as a tiebreak between two elements of same rank.
-/
noncomputable def wellOrderExtension : LinearOrder α :=
  let l : LinearOrder α := IsWellOrder.linearOrder WellOrderingRel
  @LinearOrder.lift' α (Ordinal ×ₗ α) _ (fun a : α => (WellFounded.rank.{u} hwf a, a)) fun _ _ =>
    congr_arg Prod.snd
#align well_founded.well_order_extension WellFounded.wellOrderExtension
-/

/- warning: well_founded.well_order_extension.is_well_founded_lt -> WellFounded.wellOrderExtension.isWellFounded_lt is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} {r : α -> α -> Prop} (hwf : WellFounded.{succ u1} α r), IsWellFounded.{u1} α (LinearOrder.Lt.{u1} α (WellFounded.wellOrderExtension.{u1} α r hwf))
but is expected to have type
  forall {α : Type.{u1}} {r : α -> α -> Prop} (hwf : WellFounded.{succ u1} α r), IsWellFounded.{u1} α (LT.lt.{u1} α (Preorder.toLT.{u1} α (PartialOrder.toPreorder.{u1} α (LinearOrder.toPartialOrder.{u1} α (WellFounded.wellOrderExtension.{u1} α r hwf)))))
Case conversion may be inaccurate. Consider using '#align well_founded.well_order_extension.is_well_founded_lt WellFounded.wellOrderExtension.isWellFounded_ltₓ'. -/
instance wellOrderExtension.isWellFounded_lt : IsWellFounded α hwf.wellOrderExtension.lt :=
  ⟨InvImage.wf _ <| WellFounded.prod_lex Ordinal.wellFoundedLT.wf WellOrderingRel.isWellOrder.wf⟩
#align well_founded.well_order_extension.is_well_founded_lt WellFounded.wellOrderExtension.isWellFounded_lt

#print WellFounded.exists_well_order_ge /-
/-- Any well-founded relation can be extended to a well-ordering on that type. -/
theorem exists_well_order_ge : ∃ s, r ≤ s ∧ IsWellOrder α s :=
  ⟨hwf.wellOrderExtension.lt, fun a b h => Prod.Lex.left _ _ (hwf.rank_lt_of_rel h), by constructor⟩
#align well_founded.exists_well_order_ge WellFounded.exists_well_order_ge
-/

end WellFounded

#print WellOrderExtension /-
/-- A type alias for `α`, intended to extend a well-founded order on `α` to a well-order. -/
def WellOrderExtension (α) : Type _ :=
  α
#align well_order_extension WellOrderExtension
-/

instance [Inhabited α] : Inhabited (WellOrderExtension α) :=
  ‹Inhabited (WellOrderExtension α)›

#print toWellOrderExtension /-
/-- "Identity" equivalence between a well-founded order and its well-order extension. -/
def toWellOrderExtension : α ≃ WellOrderExtension α :=
  Equiv.refl _
#align to_well_order_extension toWellOrderExtension
-/

noncomputable instance [LT α] [WellFoundedLT α] : LinearOrder (WellOrderExtension α) :=
  (IsWellFounded.wf : @WellFounded α (· < ·)).wellOrderExtension

#print WellOrderExtension.wellFoundedLT /-
instance WellOrderExtension.wellFoundedLT [LT α] [WellFoundedLT α] :
    WellFoundedLT (WellOrderExtension α) :=
  WellFounded.wellOrderExtension.isWellFounded_lt _
#align well_order_extension.well_founded_lt WellOrderExtension.wellFoundedLT
-/

#print toWellOrderExtension_strictMono /-
theorem toWellOrderExtension_strictMono [Preorder α] [WellFoundedLT α] :
    StrictMono (toWellOrderExtension : α → WellOrderExtension α) := fun a b h =>
  Prod.Lex.left _ _ <| WellFounded.rank_lt_of_rel _ h
#align to_well_order_extension_strict_mono toWellOrderExtension_strictMono
-/


import tactic

/-
When writing proofs it's easier to write them in tactic mode.
The show_term command will show you the term mode proof for this tactic proof.
If the term mode proof is shorter, this is how the proof would be written in mathlib.
-/

-- Let P and Q be propositions.
variables P Q : Prop

-- The following is a simple proof that if we have P ∧ Q, then we also have Q ∧ P
example : P ∧ Q → Q ∧ P :=
begin
  intro h,
  split,
  exact h.right,
  exact h.left,
end

-- to write this in term_mode, use the show_term command like this

example : P ∧ Q → Q ∧ P :=
begin
  show_term {
    intro h,
    split,
    exact h.right,
    exact h.left,
  },
end

-- Clicking the show_term word above and then clicking the try this command in the infoview window will reduce this to

example : P ∧ Q → Q ∧ P :=
begin
  exact λ (h : P ∧ Q), ⟨h.right, h.left⟩,
end

-- Finally we can remove the begin exact and end parts to reduce this to
example : P ∧ Q → Q ∧ P := λ (h : P ∧ Q), ⟨h.right, h.left⟩


/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.dlist
import tactic.core

namespace tactic
open expr list

meta def match_fn (fn : expr) : expr → tactic (expr × expr)
| (app (app fn' e₀) e₁) := unify fn fn' $> (e₀, e₁)
| _ := failed

meta def fill_args : expr → tactic (expr × list expr)
| (pi n bi d b) :=
do v ← mk_meta_var d,
   (r, vs) ← fill_args (b.instantiate_var v),
   return (r, v::vs)
| e := return (e, [])

meta def mk_assoc_pattern' (fn : expr) : expr → tactic (dlist expr)
| e :=
  (do (e₀, e₁) ← match_fn fn e,
      (++) <$> mk_assoc_pattern' e₀ <*> mk_assoc_pattern' e₁) <|>
  pure (dlist.singleton e)

meta def mk_assoc_pattern (fn e : expr) : tactic (list expr) :=
dlist.to_list <$> mk_assoc_pattern' fn e

meta def mk_assoc (fn : expr) : list expr → tactic expr
| [] := failed
| [x] := pure x
| (x₀ :: x₁ :: xs) := mk_assoc (fn x₀ x₁ :: xs)

meta def chain_eq_trans : list expr → tactic expr
| [] := to_expr ``(rfl)
| [e] := pure e
| (e :: es) := chain_eq_trans es >>= mk_eq_trans e

meta def unify_prefix : list expr → list expr → tactic unit
| [] _ := pure ()
| _ [] := failed
| (x :: xs) (y :: ys) :=
unify x y >> unify_prefix xs ys

meta def match_assoc_pattern' (p : list expr) : list expr → tactic (list expr × list expr) | es :=
unify_prefix p es $> ([], es.drop p.length) <|>
  match es with
  | [] := failed
  | (x :: xs) := prod.map (cons x) id <$> match_assoc_pattern' xs
  end

meta def match_assoc_pattern (fn p e : expr) : tactic (list expr × list expr) :=
do p' ← mk_assoc_pattern fn p,
   e' ← mk_assoc_pattern fn e,
   match_assoc_pattern' p' e'

/-- Tag for proofs generated by `assoc_rewrite`. -/
def id_tag.assoc_proof := ()

meta def mk_eq_proof (fn : expr) (e₀ e₁ : list expr) (p : expr) : tactic (expr × expr × expr) :=
do (l, r) ← infer_type p >>= match_eq,
   if e₀.empty ∧ e₁.empty then pure (l, r, p)
   else do
     l' ← mk_assoc fn (e₀ ++ [l] ++ e₁),
     r' ← mk_assoc fn (e₀ ++ [r] ++ e₁),
     t  ← infer_type l',
     v  ← mk_local_def `x t,
     e  ← mk_assoc fn (e₀ ++ [v] ++ e₁),
     p  ← mk_congr_arg (e.lambdas [v]) p,
     p' ← mk_app ``eq [l', r'],
     let p' := mk_tagged_proof p' p ``id_tag.assoc_proof,
     return (l', r', p')

meta def assoc_root (fn assoc : expr) : expr → tactic (expr × expr) | e :=
(do (e₀, e₁) ← match_fn fn e,
    (ea, eb) ← match_fn fn e₁,
    let e' := fn (fn e₀ ea) eb,
    p' ← mk_eq_symm (assoc e₀ ea eb),
    (e'', p'') ← assoc_root e',
    prod.mk e'' <$> mk_eq_trans p' p'') <|>
prod.mk e <$> mk_eq_refl e

meta def assoc_refl' (fn assoc : expr) : expr → expr → tactic expr
| l r := (is_def_eq l r >> mk_eq_refl l) <|> do
  (l', l_p)  ← assoc_root fn assoc l <|> fail "A",
  (el₀, el₁) ← match_fn   fn l' <|> fail "B",
  (r', r_p)  ← assoc_root fn assoc r <|> fail "C",
  (er₀, er₁) ← match_fn   fn r' <|> fail "D",
  p₀ ← assoc_refl' el₀ er₀,
  p₁ ← is_def_eq el₁ er₁ >> mk_eq_refl el₁,
  f_eq ← mk_congr_arg fn p₀ <|> fail "G",
  p' ← mk_congr f_eq p₁ <|> fail "H",
  r_p' ← mk_eq_symm r_p,
  chain_eq_trans [l_p, p', r_p']

meta def assoc_refl (fn : expr) : tactic unit :=
do (l, r) ← target >>= match_eq,
   assoc ← mk_mapp ``is_associative.assoc [none, fn, none]
     <|> fail format!"{fn} is not associative",
   assoc_refl' fn assoc l r >>= tactic.exact

meta def flatten (fn assoc e : expr) : tactic (expr × expr) :=
do ls ← mk_assoc_pattern fn e,
   e' ← mk_assoc fn ls,
   p  ← assoc_refl' fn assoc e e',
   return (e', p)

meta def assoc_rewrite_intl (assoc h e : expr) : tactic (expr × expr) :=
do t ← infer_type h,
   (lhs, rhs) ← match_eq t,
   let fn  := lhs.app_fn.app_fn,
   (l, r) ← match_assoc_pattern fn lhs e,
   (lhs', rhs', h') ← mk_eq_proof fn l r h,
   e_p ← assoc_refl' fn assoc e lhs',
   (rhs'', rhs_p) ← flatten fn assoc rhs',
   final_p ← chain_eq_trans [e_p, h', rhs_p],
   return (rhs'', final_p)

-- TODO(Simon): visit expressions built of `fn` nested inside other such expressions:
-- e.g.: x + f (a + b + c) + y should generate two rewrite candidates
meta def enum_assoc_subexpr' (fn : expr) : expr → tactic (dlist expr)
| e :=
  dlist.singleton e <$ (match_fn fn e >> guard (¬ e.has_var)) <|>
  expr.mfoldl (λ es e', (++ es) <$> enum_assoc_subexpr' e') dlist.empty e

meta def enum_assoc_subexpr (fn e : expr) : tactic (list expr) :=
dlist.to_list <$> enum_assoc_subexpr' fn e

meta def mk_assoc_instance (fn : expr) : tactic expr :=
do t ← mk_mapp ``is_associative [none, fn],
   inst ← prod.snd <$> solve_aux t assumption <|>
     (mk_instance t >>= assertv `_inst t) <|>
     fail format!"{fn} is not associative",
   mk_mapp ``is_associative.assoc [none, fn, inst]

meta def assoc_rewrite (h e : expr) (opt_assoc : option expr := none) :
  tactic (expr × expr × list expr) :=
do (t, vs) ← infer_type h >>= fill_args,
   (lhs, rhs) ← match_eq t,
   let fn := lhs.app_fn.app_fn,
   es ← enum_assoc_subexpr fn e,
   assoc ← match opt_assoc with
           | none := mk_assoc_instance fn
           | (some assoc) := pure assoc
           end,
   (_, p) ← mfirst (assoc_rewrite_intl assoc $ h.mk_app vs) es,
   (e', p', _) ← tactic.rewrite p e,
   pure (e', p', vs)

meta def assoc_rewrite_target (h : expr) (opt_assoc : option expr :=  none) :
  tactic unit :=
do tgt ← target,
   (tgt', p, _) ← assoc_rewrite h tgt opt_assoc,
   replace_target tgt' p

meta def assoc_rewrite_hyp (h hyp : expr) (opt_assoc : option expr := none) :
  tactic expr :=
do tgt ← infer_type hyp,
   (tgt', p, _) ← assoc_rewrite h tgt opt_assoc,
   replace_hyp hyp tgt' p

namespace interactive

setup_tactic_parser

private meta def assoc_rw_goal (rs : list rw_rule) : tactic unit :=
rs.mmap' $ λ r, do
 save_info r.pos,
 eq_lemmas ← get_rule_eqn_lemmas r,
 orelse'
   (do e ← to_expr' r.rule, assoc_rewrite_target e)
   (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_target e)
   (eq_lemmas.empty)

private meta def uses_hyp (e : expr) (h : expr) : bool :=
e.fold ff $ λ t _ r, r || (t = h)

private meta def assoc_rw_hyp : list rw_rule → expr → tactic unit
| []      hyp := skip
| (r::rs) hyp := do
  save_info r.pos,
  eq_lemmas ← get_rule_eqn_lemmas r,
  orelse'
    (do e ← to_expr' r.rule, when (¬ uses_hyp e hyp) $ assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs)
    (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs)
    (eq_lemmas.empty)

private meta def assoc_rw_core (rs : parse rw_rules) (loca : parse location) : tactic unit :=
match loca with
| loc.wildcard := loca.try_apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules)
| _            := loca.apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules)
end >> try reflexivity
    >> try (returnopt rs.end_pos >>= save_info)

/--
`assoc_rewrite [h₀,← h₁] at ⊢ h₂` behaves like `rewrite [h₀,← h₁] at ⊢ h₂`
with the exception that associativity is used implicitly to make rewriting
possible.

It works for any function `f` for which an `is_associative f` instance can be found.

```
example {α : Type*} (f : α → α → α) [is_associative α f] (a b c d x : α) :
  let infix ` ~ ` := f in
  b ~ c = x → (a ~ b ~ c ~ d) = (a ~ x ~ d) :=
begin
  intro h,
  assoc_rw h,
end
```
-/
meta def assoc_rewrite (q : parse rw_rules) (l : parse location) : tactic unit :=
propagate_tags (assoc_rw_core q l)

/-- synonym for `assoc_rewrite` -/
meta def assoc_rw (q : parse rw_rules) (l : parse location) : tactic unit :=
assoc_rewrite q l

add_tactic_doc
{ name                     := "assoc_rewrite",
  category                 := doc_category.tactic,
  decl_names               := [`tactic.interactive.assoc_rewrite, `tactic.interactive.assoc_rw],
  tags                     := ["rewriting"],
  inherit_description_from := `tactic.interactive.assoc_rewrite }

end interactive
end tactic


import logic.equiv.basic
import tactic.norm_swap

open equiv tactic

/--
To properly test that norm_swap works without the help of the simplifier,
we turn off the simp lemmas that simplify swaps of the form
`swap x y x = y` and `swap x y y = x`.
-/
local attribute [-simp] swap_apply_left
local attribute [-simp] swap_apply_right

/--
We can check all possibilities of swapping of `0, 1, bit0 _, bit1 _` using the
64 combinations of `[0, 1, 2, 3]`. This example should execute and complete without error,
if `norm_swap.eval` is behaving properly.
-/
example : true := by do
  let l : list ℕ := [0, 1, 2, 3],
  let l' : list ((ℕ × ℕ) × ℕ) := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
  (lhs : list expr) ← mmap (λ (tup : (ℕ × ℕ) × ℕ),
    to_expr ``(equiv.swap %%tup.fst.fst %%tup.fst.snd %%tup.snd)) l',
  (rhs : list expr) ← mmap (λ (tup : (ℕ × ℕ) × ℕ),
    if tup.snd = tup.fst.fst then to_expr ``(%%tup.fst.snd)
    else if tup.snd = tup.fst.snd then to_expr ``(%%tup.fst.fst)
    else to_expr ``(%%tup.snd)) l',
  let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℕ %%L %%R)) lhs rhs,
  g ← get_goals,
  gls ← mmap mk_meta_var eqs,
  set_goals $ g ++ gls,
  triv, -- to discharge the starting `true` goal
  repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
  done

example : true := by do
  let l : list ℤ := [0, 2, -1, 3, -4],
  let l' := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
  ic ← mk_instance_cache `(ℤ),
  -- we have to convert the provided `int`s into numeral form for the goals
  -- to look like what they would usually: `⇑(swap -1 3) -4 = -4`, instead of
-- `⇑(swap (int.neg_succ_of_nat 0) (int.of_nat 3)) (int.neg_succ_of_nat 3) = int.neg_succ_of_nat 3`
  el ← mmap (λ (tup : (ℤ × ℤ) × ℤ), do
    (_, a) ← ic.of_int tup.fst.fst,
    (_, b) ← ic.of_int tup.fst.snd,
    (_, c) ← ic.of_int tup.snd,
    pure ((a, b), c)) l',
  (lhs : list expr) ← mmap (λ (tup : (expr × expr) × expr),
    to_expr ``((equiv.swap %%tup.fst.fst %%tup.fst.snd) %%tup.snd)) el,
  let rhs : list expr := el.map (λ (tup : (expr × expr) × expr),
    if tup.snd = tup.fst.fst then tup.fst.snd
    else if tup.snd = tup.fst.snd then tup.fst.fst
    else tup.snd),
  let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℤ %%L %%R)) lhs rhs,
  g ← get_goals,
  gls ← mmap mk_meta_var eqs,
  set_goals $ g ++ gls,
  triv, -- to discharge the starting `true` goal
  repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
  done

example : true := by do
  let l : list ℚ := [0, (2 : ℚ) / -2, -1, 3 / 5, 4],
  let l' := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
  ic ← mk_instance_cache `(ℚ),
  -- we have to convert the provided `rat`s into numeral form for the goals
  -- to look like what they would usually: `⇑(swap -1 3) -4 = -4`, like with ℤ above
  el ← mmap (λ (tup : (ℚ × ℚ) × ℚ), do
    (_, a) ← ic.of_rat tup.fst.fst,
    (_, b) ← ic.of_rat tup.fst.snd,
    (_, c) ← ic.of_rat tup.snd,
    pure ((a, b), c)) l',
  (lhs : list expr) ← mmap (λ (tup : (expr × expr) × expr),
    to_expr ``((equiv.swap %%tup.fst.fst %%tup.fst.snd) %%tup.snd)) el,
  let rhs : list expr := el.map (λ (tup : (expr × expr) × expr),
    if tup.snd = tup.fst.fst then tup.fst.snd
    else if tup.snd = tup.fst.snd then tup.fst.fst
    else tup.snd),
  let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℚ %%L %%R)) lhs rhs,
  g ← get_goals,
  gls ← mmap mk_meta_var eqs,
  set_goals $ g ++ gls,
  triv, -- to discharge the starting `true` goal
  repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
  done

example : swap (3 : fin 7) 5 0 = 0 := by norm_num
example : swap (fin.succ 2 : fin 7) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 5 3 = 5 := by norm_num
example : swap (3 : fin 1) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 5 10 = 12 := by norm_fin
example : swap (2 : fin 7) 4 9 = 11 := by norm_fin
example : swap (3 : fin 7) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 12 9 = 2 := by norm_num
example : swap (0 : fin (1 + 2)) (1 : fin (nat.succ (1 + 1))) ((fin.succ 1) : fin 3) = 2 :=
by norm_num

-- norm_swap doesn't generate trace output on non-swap expressions
example : (1 : ℤ) = (1 : ℕ) := by norm_num


/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.card
import data.finset.option

/-!
# fintype instances for option

> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/

open function
open_locale nat

universes u v

variables {α β γ : Type*}

open finset function

instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩

lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl

@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
  fintype.card (option α) = fintype.card α + 1 :=
(finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl

/-- If `option α` is a `fintype` then so is `α` -/
def fintype_of_option {α : Type*} [fintype (option α)] : fintype α :=
⟨finset.erase_none (fintype.elems (option α)), λ x, mem_erase_none.mpr (fintype.complete (some x))⟩

/-- A type is a `fintype` if its successor (using `option`) is a `fintype`. -/
def fintype_of_option_equiv [fintype α] (f : α ≃ option β) : fintype β :=
by { haveI := fintype.of_equiv _ f, exact fintype_of_option }

namespace fintype

/-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
def trunc_rec_empty_option {P : Type u → Sort v}
  (of_equiv : ∀ {α β}, α ≃ β → P α → P β)
  (h_empty : P pempty)
  (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α))
  (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) :=
begin
  suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)),
  { apply trunc.bind (this (fintype.card α)),
    intro h,
    apply trunc.map _ (fintype.trunc_equiv_fin α),
    intro e,
    exact of_equiv (equiv.ulift.trans e.symm) h },
  intro n,
  induction n with n ih,
  { have : card pempty = card (ulift (fin 0)),
    { simp only [card_fin, card_pempty, card_ulift] },
    apply trunc.bind (trunc_equiv_of_card_eq this),
    intro e,
    apply trunc.mk,
    refine of_equiv e h_empty, },
  { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)),
    { simp only [card_fin, card_option, card_ulift] },
    apply trunc.bind (trunc_equiv_of_card_eq this),
    intro e,
    apply trunc.map _ ih,
    intro ih,
    refine of_equiv e (h_option ih), },
end

/-- An induction principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
@[elab_as_eliminator]
lemma induction_empty_option {P : Π (α : Type u) [fintype α], Prop}
  (of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›)
  (h_empty : P pempty)
  (h_option : ∀ α [fintype α], by exactI P α → P (option α))
  (α : Type u) [fintype α] : P α :=
begin
  obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h)
    (λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty)
    _ α _ (classical.dec_eq α),
  { exact p _ },
  { rintro α hα - Pα hα', resetI, convert h_option α (Pα _) }
end

end fintype

/-- An induction principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
lemma finite.induction_empty_option {P : Type u → Prop}
  (of_equiv : ∀ {α β}, α ≃ β → P α → P β)
  (h_empty : P pempty)
  (h_option : ∀ {α} [fintype α], P α → P (option α))
  (α : Type u) [finite α] : P α :=
begin
  casesI nonempty_fintype α,
  refine fintype.induction_empty_option _ _ _ α,
  exacts [λ α β _, of_equiv, h_empty, @h_option]
end


/-
Copyright (c) 2021 Jakob Scholbach. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob Scholbach
-/
import category_theory.arrow
import category_theory.limits.preserves.shapes.terminal

/-!
# Lifting properties

This file defines the lifting property of two arrows in a category and shows basic properties of
this notion.
We also construct the subcategory consisting of those morphisms which have the right lifting
property with respect to arrows in a given diagram.

## Main results
- `has_lifting_property`: the definition of the lifting property
- `iso_has_right_lifting_property`: any isomorphism satisfies the right lifting property (rlp)
- `id_has_right_lifting_property`: any identity has the rlp
- `right_lifting_property_initial_iff`: spells out the rlp with respect to a map whose source is an
  initial object
- `right_lifting_subcat`: given a set of arrows `F : D → arrow C`, we construct the subcategory
  of those morphisms `p` in `C` that satisfy the rlp w.r.t. `F i`, for any element `i` of `D`.

## Tags
lifting property
-/

open category_theory.limits

namespace category_theory

universes v u v₁
variables {C : Type u} [category.{v} C]
variables {D : Type v₁}

variables {X Y Z : C}

/-- The lifting property of a morphism `i` with respect to a morphism `p`.
This can be interpreted as the right lifting property of `i` with respect to `p`,
or the left lifting property of `p` with respect to `i`. -/
class has_lifting_property (i p : arrow C) : Prop :=
(sq_has_lift : ∀ (sq : i ⟶ p), arrow.has_lift sq)

@[priority 100] -- see Note [lower instance priority]
instance has_lifting_property' {i p : arrow C} [has_lifting_property i p] (sq : i ⟶ p) :
  arrow.has_lift sq :=
has_lifting_property.sq_has_lift sq

/-- Any isomorphism has the right lifting property with respect to any map.
A    → X
↓i    ↓p≅
B    → Y
-/
lemma iso_has_right_lifting_property (i : arrow C) (p : X ≅ Y) :
  has_lifting_property i (arrow.mk p.hom) :=
⟨λ sq, ⟨⟨{ lift := sq.right ≫ p.inv, }⟩⟩⟩ -- the lift is obtained by p⁻¹ ∘ (B → Y)

/-- Any identity has the right lifting property with respect to any map. -/
lemma id_has_right_lifting_property (i : arrow C) : has_lifting_property i (arrow.mk (𝟙 X)) :=
iso_has_right_lifting_property i (iso.refl _)

/-- An equivalent characterization for right lifting with respect to a map `i` whose source is
initial.
∅ → X
↓   ↓
B → Y has a lifting iff there is a map B → X making the right part commute.
-/
lemma right_lifting_property_initial_iff (i p : arrow C) (h : is_initial i.left) :
  has_lifting_property i p ↔ ∀ {e : i.right ⟶ p.right}, ∃ l : i.right ⟶ p.left, l ≫ p.hom = e :=
begin
  fsplit,
  { introsI hlift e,
    have comm : (is_initial.to h p.left) ≫ p.hom = i.hom ≫ e :=
      is_initial.hom_ext h _ _,
    use arrow.lift (arrow.hom_mk comm),
    simp },
  { refine λ hlift, ⟨λ sq, _⟩,
    obtain ⟨l, hl⟩ : ∃ (l : i.right ⟶ p.left), l ≫ p.hom = sq.right := hlift,
    exact arrow.has_lift.mk ⟨l, is_initial.hom_ext h _ _⟩, }
end

/-- The condition of having the rlp with respect to a morphism `i` is stable under composition. -/
lemma has_right_lifting_property_comp {i : arrow C} {f : X ⟶ Y} {g : Y ⟶ Z}
  (hf : has_lifting_property i (arrow.mk f))
  (hg : has_lifting_property i (arrow.mk g)) :
  has_lifting_property i (arrow.mk (f ≫ g)) :=
{ sq_has_lift := λ sq1,
    -- construct a square i ⟶ f
    let sq2 : i ⟶ (arrow.mk f) := ⟨sq1.left, arrow.lift (arrow.square_to_snd sq1)⟩ in
    -- show that the lift of this square is a lift of i with respect to g ∘ f
    ⟨⟨⟨(arrow.lift sq2 : _ ⟶ _), by simp⟩⟩⟩ }

/-- The objects of the subcategory `right_lifting_subcategory` are the ones in the
underlying category. -/
def right_lifting_subcat (R : Type u) := R

instance right_lifting_subcat.inhabited  (R : Type u) [inhabited R] :
  inhabited (right_lifting_subcat R) :=
{ default := (default R : R) }

/-- The objects of the subcategory `right_lifting_subcategory` are the ones in the
underlying category. -/
def right_lifting_subcat.X {R : Type u} (x : right_lifting_subcat R) : R := x

lemma id_has_right_lifting_property' {F : D → arrow C} (X : C) :
  ∀ i : D, has_lifting_property (F i) (arrow.mk (𝟙 X)) :=
λ i, id_has_right_lifting_property (F i)

lemma has_right_lifting_property_comp'
  {F : D → arrow C} {f : X ⟶ Y} (hf : ∀ i : D, has_lifting_property (F i) (arrow.mk f))
  {g : Y ⟶ Z} (hg : ∀ i : D, has_lifting_property (F i) (arrow.mk g)) :
  ∀ i : D,  has_lifting_property (F i) (arrow.mk (f ≫ g)) :=
λ i, has_right_lifting_property_comp (hf i) (hg i)

/-- Given a set of arrows in C, indexed by `F : D → arrow C`,
we construct the (non-full) subcategory of `C`
spanned by those morphisms that have the right lifting property relative to all maps
of the form `F i`, where `i` is any element in `D`. -/
def right_lifting_subcategory (F : D → arrow C) : category (right_lifting_subcat C) :=
{ hom := λ X Y, { p : X ⟶ Y // ∀ {i : D}, has_lifting_property (F i) (arrow.mk p) },
  id := λ X, ⟨𝟙 X, id_has_right_lifting_property' X⟩,
  comp := λ X Y Z f g, ⟨f.val ≫ g.val, has_right_lifting_property_comp' f.property g.property⟩ }

end category_theory


import linear_algebra.finsupp
import missing_mathlib.data.finsupp
import missing_mathlib.algebra.big_operators
import missing_mathlib.linear_algebra.basic

import analysis.complex.polynomial

lemma finsupp.total_on_finset {α β γ : Type*}
  [decidable_eq α] [decidable_eq β] [decidable_eq γ] [ring β] [add_comm_group γ] [module β γ]
  (s : finset α) (f : α → β) (g : α → γ) (hf : ∀ a, f a ≠ 0 → a ∈ s):
  finsupp.total α γ β g (finsupp.on_finset s f hf) =
    finset.sum (finset.filter (λ (a : α), f a ≠ 0) s) (λ (x : α), f x • g x) :=
begin
  rw finsupp.total_apply,
  dunfold finsupp.sum,
  simp [finsupp.on_finset_apply],
  rw finsupp.on_finset_support
end


import tactic
import .lesson3

noncomputable theory
open_locale classical

open PreHilbertPlane
open HilbertPlane

section plane_separation

variables {Ω : Type*} [HilbertPlane Ω]

variables {A B C : Ω}
variables {ℓ r s : Line Ω}

lemma auxiliary_point (ℓ : Line Ω) (h : collinear_triple A B C) (hA : ¬ A ∈ ℓ) (hB : ¬ B ∈ ℓ)
	(hC : ¬ C ∈ ℓ) (hAB : A ≠ B) (hAC : A ≠ C) (hBC : B ≠ C)  :
	∃ (D E : Ω), D ∈ ℓ ∧ ¬ E ∈ ℓ ∧ same_side ℓ A E ∧ (D * A * E) ∧
					¬ collinear_triple A B E ∧
					¬ collinear_triple E C B ∧
					¬ collinear_triple A C E  :=
begin
	obtain ⟨ m, ⟨hAm, hBm, hCm⟩ ⟩ := h,
	obtain rfl | ℓ_not_m := em(ℓ = m),
		tauto,
	have HD : ∃ (D : Ω), D ∈ ℓ ∧ D ∉ m := point_in_line_difference ℓ_not_m,
	rcases HD with ⟨D ,⟨hDℓ, hDm⟩⟩,
	have hDA : D ≠ A,
	{
		intro hda,
		subst hda,
		exact hDm hAm,
	},
	have HE : ∃ E : Ω, D * A * E := HilbertPlane.B2 hDA,
	cases HE with E hE,
	have hDAE : collinear_triple D A E := (HilbertPlane.B12 hE).2.2.2,
	rcases hDAE with ⟨ 	s, ⟨ hDs,hAs, hEs⟩⟩,

	have ℓ_not_s : ℓ ≠ s,
	{
		intro hℓs,
		subst hℓs,
		exact ℓ_not_m (false.rec (ℓ = m) (hA hAs)),
	},
	have E_notin_ℓ : E ∉ ℓ,
	{
		intro hEℓ,
		apply (HilbertPlane.B12 hE).2.1,
		apply distinct_lines_have_at_most_one_common_point ℓ_not_s hDℓ hDs hEℓ hEs,
	},
	have hAE : same_side ℓ A E,
	{
		unfold same_side,
		repeat {split},
		repeat {assumption},
		right,
		ext1,
		norm_num,
		rintros (rfl | rfl|  h), repeat {assumption},
		{
			intro hxℓ,
			have x_is_D : x = D,
			{
				apply distinct_lines_have_at_most_one_common_point ℓ_not_s,
				repeat {assumption},
				exact between_points_share_line hAs hEs h,
			},
			subst x_is_D,
			have hxAE : collinear_triple x A E := (HilbertPlane.B12 hE).2.2.2,
			have Hfin := HilbertPlane.B3 hxAE,
			unfold xor3 at Hfin,
			tauto,
		},
	},
	have E_notin_m : E ∉ m,
	{
		intro hEm,
		have hsm : s = m := I12 (HilbertPlane.B12 hE).2.2.1 hAs hEs hAm hEm,
		subst hsm,
		tauto,
	},
	use [D, E],
	unfold same_side at hAE,
	repeat {split},
	repeat {tauto},
	all_goals
	{
		intro h,
		obtain ⟨ t, ⟨ hAt, hBt, hEt⟩⟩ := h,
		have m_eq_t : m = t,
		{
			try {apply equal_lines_of_contain_two_points hAB; assumption,},
			try {apply equal_lines_of_contain_two_points hBC; assumption,},
			try {apply equal_lines_of_contain_two_points hAC; assumption,},
		},
		subst m_eq_t,
		tauto,
	},
end

lemma same_side.trans : same_side ℓ A B → same_side ℓ B C → same_side ℓ A C :=
begin
intros hAB hBC,
by_cases ¬ collinear_triple A B C,
{
	apply same_side_trans_of_noncollinear _ hAB hBC,
	rw collinear_triple_of_equal A C B A B C,
	exact h,
},
{
	-- A B C collinear
	push_neg at h,
	obtain rfl | hAeqB := em(A = B), assumption,
	obtain rfl | hBeqC := em(B = C), assumption,
	obtain rfl | hAeqC := em(A = C), exact same_side.refl,
    have H1 := point_on_line_of_same_side hAB,
    have H2 := point_on_line_of_same_side hBC,
    by_cases hAℓ : A ∈ ℓ,
    {
        left,
        split;
        {
            try {rw [←H2, ←H1]},
            exact hAℓ,
        },
    },
	obtain ⟨D,E, ⟨ hDℓ, hEℓ, hAE, hDAE, hABE, hECB, hACE⟩⟩ :=
		auxiliary_point ℓ h _ _ _ _ _ _,
	{
		rw collinear_triple_of_equal A B E B E A at hABE,
		have hBE : same_side ℓ B E :=
			same_side_trans_of_noncollinear hABE (same_side.symm hAB) hAE,
		have hEC : same_side ℓ E C :=
			same_side_trans_of_noncollinear hECB (same_side.symm hBE) hBC,
		apply same_side_trans_of_noncollinear hACE hAE hEC,
	},
	repeat {tauto},
},
end

end plane_separation


/-
Copyright (c) 2021 Alex J. Best. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex J. Best

! This file was ported from Lean 3 source module algebra.module.pointwise_pi
! leanprover-community/mathlib commit f2f413b9d4be3a02840d0663dace76e8fe3da053
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Set.Pointwise.Smul
import Mathbin.GroupTheory.GroupAction.Pi

/-!
# Pointwise actions on sets in Pi types

> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.

This file contains lemmas about pointwise actions on sets in Pi types.

## Tags

set multiplication, set addition, pointwise addition, pointwise multiplication, pi

-/

open Pointwise

open Set

variable {K ι : Type _} {R : ι → Type _}

/- warning: smul_pi_subset -> smul_pi_subset is a dubious translation:
lean 3 declaration is
  forall {K : Type.{u1}} {ι : Type.{u2}} {R : ι -> Type.{u3}} [_inst_1 : forall (i : ι), SMul.{u1, u3} K (R i)] (r : K) (s : Set.{u2} ι) (t : forall (i : ι), Set.{u3} (R i)), HasSubset.Subset.{max u2 u3} (Set.{max u2 u3} (forall (i : ι), R i)) (Set.hasSubset.{max u2 u3} (forall (i : ι), R i)) (SMul.smul.{u1, max u2 u3} K (Set.{max u2 u3} (forall (i : ι), R i)) (Set.smulSet.{u1, max u2 u3} K (forall (i : ι), R i) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => R i) (fun (i : ι) => _inst_1 i))) r (Set.pi.{u2, u3} ι (fun (i : ι) => R i) s t)) (Set.pi.{u2, u3} ι (fun (i : ι) => R i) s (SMul.smul.{u1, max u2 u3} K (forall (i : ι), Set.{u3} (R i)) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => Set.{u3} (R i)) (fun (i : ι) => Set.smulSet.{u1, u3} K (R i) (_inst_1 i))) r t))
but is expected to have type
  forall {K : Type.{u3}} {ι : Type.{u1}} {R : ι -> Type.{u2}} [_inst_1 : forall (i : ι), SMul.{u3, u2} K (R i)] (r : K) (s : Set.{u1} ι) (t : forall (i : ι), Set.{u2} (R i)), HasSubset.Subset.{max u1 u2} (Set.{max u1 u2} (forall (i : ι), R i)) (Set.instHasSubsetSet.{max u1 u2} (forall (i : ι), R i)) (HSMul.hSMul.{u3, max u2 u1, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.{max u1 u2} (forall (i : ι), R i)) (instHSMul.{u3, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.smulSet.{u3, max u1 u2} K (forall (i : ι), R i) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => R i) (fun (i : ι) => _inst_1 i)))) r (Set.pi.{u1, u2} ι (fun (i : ι) => R i) s t)) (Set.pi.{u1, u2} ι (fun (i : ι) => R i) s (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (forall (i : ι), Set.{u2} (R i)) (instHSMul.{u3, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => Set.{u2} (R i)) (fun (i : ι) => Set.smulSet.{u3, u2} K (R i) (_inst_1 i)))) r t))
Case conversion may be inaccurate. Consider using '#align smul_pi_subset smul_pi_subsetₓ'. -/
@[to_additive]
theorem smul_pi_subset [∀ i, SMul K (R i)] (r : K) (s : Set ι) (t : ∀ i, Set (R i)) :
    r • pi s t ⊆ pi s (r • t) := by
  rintro x ⟨y, h, rfl⟩ i hi
  exact smul_mem_smul_set (h i hi)
#align smul_pi_subset smul_pi_subset
#align vadd_pi_subset vadd_pi_subset

/- warning: smul_univ_pi -> smul_univ_pi is a dubious translation:
lean 3 declaration is
  forall {K : Type.{u1}} {ι : Type.{u2}} {R : ι -> Type.{u3}} [_inst_1 : forall (i : ι), SMul.{u1, u3} K (R i)] (r : K) (t : forall (i : ι), Set.{u3} (R i)), Eq.{succ (max u2 u3)} (Set.{max u2 u3} (forall (i : ι), R i)) (SMul.smul.{u1, max u2 u3} K (Set.{max u2 u3} (forall (i : ι), R i)) (Set.smulSet.{u1, max u2 u3} K (forall (i : ι), R i) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => R i) (fun (i : ι) => _inst_1 i))) r (Set.pi.{u2, u3} ι (fun (i : ι) => R i) (Set.univ.{u2} ι) t)) (Set.pi.{u2, u3} ι (fun (i : ι) => R i) (Set.univ.{u2} ι) (SMul.smul.{u1, max u2 u3} K (forall (i : ι), Set.{u3} (R i)) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => Set.{u3} (R i)) (fun (i : ι) => Set.smulSet.{u1, u3} K (R i) (_inst_1 i))) r t))
but is expected to have type
  forall {K : Type.{u3}} {ι : Type.{u1}} {R : ι -> Type.{u2}} [_inst_1 : forall (i : ι), SMul.{u3, u2} K (R i)] (r : K) (t : forall (i : ι), Set.{u2} (R i)), Eq.{max (succ u1) (succ u2)} (Set.{max u1 u2} (forall (i : ι), R i)) (HSMul.hSMul.{u3, max u2 u1, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.{max u1 u2} (forall (i : ι), R i)) (instHSMul.{u3, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.smulSet.{u3, max u1 u2} K (forall (i : ι), R i) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => R i) (fun (i : ι) => _inst_1 i)))) r (Set.pi.{u1, u2} ι (fun (i : ι) => R i) (Set.univ.{u1} ι) t)) (Set.pi.{u1, u2} ι (fun (i : ι) => R i) (Set.univ.{u1} ι) (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (forall (i : ι), Set.{u2} (R i)) (instHSMul.{u3, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => Set.{u2} (R i)) (fun (i : ι) => Set.smulSet.{u3, u2} K (R i) (_inst_1 i)))) r t))
Case conversion may be inaccurate. Consider using '#align smul_univ_pi smul_univ_piₓ'. -/
@[to_additive]
theorem smul_univ_pi [∀ i, SMul K (R i)] (r : K) (t : ∀ i, Set (R i)) :
    r • pi (univ : Set ι) t = pi (univ : Set ι) (r • t) :=
  Subset.antisymm (smul_pi_subset _ _ _) fun x h =>
    by
    refine' ⟨fun i => Classical.choose (h i <| Set.mem_univ _), fun i hi => _, funext fun i => _⟩
    · exact (Classical.choose_spec (h i _)).left
    · exact (Classical.choose_spec (h i _)).right
#align smul_univ_pi smul_univ_pi
#align vadd_univ_pi vadd_univ_pi

/- warning: smul_pi -> smul_pi is a dubious translation:
lean 3 declaration is
  forall {K : Type.{u1}} {ι : Type.{u2}} {R : ι -> Type.{u3}} [_inst_1 : Group.{u1} K] [_inst_2 : forall (i : ι), MulAction.{u1, u3} K (R i) (DivInvMonoid.toMonoid.{u1} K (Group.toDivInvMonoid.{u1} K _inst_1))] (r : K) (S : Set.{u2} ι) (t : forall (i : ι), Set.{u3} (R i)), Eq.{succ (max u2 u3)} (Set.{max u2 u3} (forall (i : ι), R i)) (SMul.smul.{u1, max u2 u3} K (Set.{max u2 u3} (forall (i : ι), R i)) (Set.smulSet.{u1, max u2 u3} K (forall (i : ι), R i) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => R i) (fun (i : ι) => MulAction.toHasSmul.{u1, u3} K (R i) (DivInvMonoid.toMonoid.{u1} K (Group.toDivInvMonoid.{u1} K _inst_1)) (_inst_2 i)))) r (Set.pi.{u2, u3} ι (fun (i : ι) => R i) S t)) (Set.pi.{u2, u3} ι (fun (i : ι) => R i) S (SMul.smul.{u1, max u2 u3} K (forall (i : ι), Set.{u3} (R i)) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => Set.{u3} (R i)) (fun (i : ι) => Set.smulSet.{u1, u3} K (R i) (MulAction.toHasSmul.{u1, u3} K (R i) (DivInvMonoid.toMonoid.{u1} K (Group.toDivInvMonoid.{u1} K _inst_1)) (_inst_2 i)))) r t))
but is expected to have type
  forall {K : Type.{u3}} {ι : Type.{u1}} {R : ι -> Type.{u2}} [_inst_1 : Group.{u3} K] [_inst_2 : forall (i : ι), MulAction.{u3, u2} K (R i) (DivInvMonoid.toMonoid.{u3} K (Group.toDivInvMonoid.{u3} K _inst_1))] (r : K) (S : Set.{u1} ι) (t : forall (i : ι), Set.{u2} (R i)), Eq.{max (succ u1) (succ u2)} (Set.{max u1 u2} (forall (i : ι), R i)) (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.{max u1 u2} (forall (i : ι), R i)) (instHSMul.{u3, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.smulSet.{u3, max u1 u2} K (forall (i : ι), R i) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => R i) (fun (i : ι) => MulAction.toSMul.{u3, u2} K (R i) (DivInvMonoid.toMonoid.{u3} K (Group.toDivInvMonoid.{u3} K _inst_1)) (_inst_2 i))))) r (Set.pi.{u1, u2} ι (fun (i : ι) => R i) S t)) (Set.pi.{u1, u2} ι (fun (i : ι) => R i) S (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (forall (i : ι), Set.{u2} (R i)) (instHSMul.{u3, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => Set.{u2} (R i)) (fun (i : ι) => Set.smulSet.{u3, u2} K (R i) (MulAction.toSMul.{u3, u2} K (R i) (DivInvMonoid.toMonoid.{u3} K (Group.toDivInvMonoid.{u3} K _inst_1)) (_inst_2 i))))) r t))
Case conversion may be inaccurate. Consider using '#align smul_pi smul_piₓ'. -/
@[to_additive]
theorem smul_pi [Group K] [∀ i, MulAction K (R i)] (r : K) (S : Set ι) (t : ∀ i, Set (R i)) :
    r • S.pi t = S.pi (r • t) :=
  Subset.antisymm (smul_pi_subset _ _ _) fun x h =>
    ⟨r⁻¹ • x, fun i hiS => mem_smul_set_iff_inv_smul_mem.mp (h i hiS), smul_inv_smul _ _⟩
#align smul_pi smul_pi
#align vadd_pi vadd_pi

/- warning: smul_pi₀ -> smul_pi₀ is a dubious translation:
lean 3 declaration is
  forall {K : Type.{u1}} {ι : Type.{u2}} {R : ι -> Type.{u3}} [_inst_1 : GroupWithZero.{u1} K] [_inst_2 : forall (i : ι), MulAction.{u1, u3} K (R i) (MonoidWithZero.toMonoid.{u1} K (GroupWithZero.toMonoidWithZero.{u1} K _inst_1))] {r : K} (S : Set.{u2} ι) (t : forall (i : ι), Set.{u3} (R i)), (Ne.{succ u1} K r (OfNat.ofNat.{u1} K 0 (OfNat.mk.{u1} K 0 (Zero.zero.{u1} K (MulZeroClass.toHasZero.{u1} K (MulZeroOneClass.toMulZeroClass.{u1} K (MonoidWithZero.toMulZeroOneClass.{u1} K (GroupWithZero.toMonoidWithZero.{u1} K _inst_1)))))))) -> (Eq.{succ (max u2 u3)} (Set.{max u2 u3} (forall (i : ι), R i)) (SMul.smul.{u1, max u2 u3} K (Set.{max u2 u3} (forall (i : ι), R i)) (Set.smulSet.{u1, max u2 u3} K (forall (i : ι), R i) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => R i) (fun (i : ι) => MulAction.toHasSmul.{u1, u3} K (R i) (MonoidWithZero.toMonoid.{u1} K (GroupWithZero.toMonoidWithZero.{u1} K _inst_1)) (_inst_2 i)))) r (Set.pi.{u2, u3} ι (fun (i : ι) => R i) S t)) (Set.pi.{u2, u3} ι (fun (i : ι) => R i) S (SMul.smul.{u1, max u2 u3} K (forall (i : ι), Set.{u3} (R i)) (Pi.instSMul.{u2, u3, u1} ι K (fun (i : ι) => Set.{u3} (R i)) (fun (i : ι) => Set.smulSet.{u1, u3} K (R i) (MulAction.toHasSmul.{u1, u3} K (R i) (MonoidWithZero.toMonoid.{u1} K (GroupWithZero.toMonoidWithZero.{u1} K _inst_1)) (_inst_2 i)))) r t)))
but is expected to have type
  forall {K : Type.{u3}} {ι : Type.{u1}} {R : ι -> Type.{u2}} [_inst_1 : GroupWithZero.{u3} K] [_inst_2 : forall (i : ι), MulAction.{u3, u2} K (R i) (MonoidWithZero.toMonoid.{u3} K (GroupWithZero.toMonoidWithZero.{u3} K _inst_1))] {r : K} (S : Set.{u1} ι) (t : forall (i : ι), Set.{u2} (R i)), (Ne.{succ u3} K r (OfNat.ofNat.{u3} K 0 (Zero.toOfNat0.{u3} K (MonoidWithZero.toZero.{u3} K (GroupWithZero.toMonoidWithZero.{u3} K _inst_1))))) -> (Eq.{max (succ u1) (succ u2)} (Set.{max u1 u2} (forall (i : ι), R i)) (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.{max u1 u2} (forall (i : ι), R i)) (instHSMul.{u3, max u1 u2} K (Set.{max u1 u2} (forall (i : ι), R i)) (Set.smulSet.{u3, max u1 u2} K (forall (i : ι), R i) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => R i) (fun (i : ι) => MulAction.toSMul.{u3, u2} K (R i) (MonoidWithZero.toMonoid.{u3} K (GroupWithZero.toMonoidWithZero.{u3} K _inst_1)) (_inst_2 i))))) r (Set.pi.{u1, u2} ι (fun (i : ι) => R i) S t)) (Set.pi.{u1, u2} ι (fun (i : ι) => R i) S (HSMul.hSMul.{u3, max u1 u2, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (forall (i : ι), Set.{u2} (R i)) (instHSMul.{u3, max u1 u2} K (forall (i : ι), Set.{u2} (R i)) (Pi.instSMul.{u1, u2, u3} ι K (fun (i : ι) => Set.{u2} (R i)) (fun (i : ι) => Set.smulSet.{u3, u2} K (R i) (MulAction.toSMul.{u3, u2} K (R i) (MonoidWithZero.toMonoid.{u3} K (GroupWithZero.toMonoidWithZero.{u3} K _inst_1)) (_inst_2 i))))) r t)))
Case conversion may be inaccurate. Consider using '#align smul_pi₀ smul_pi₀ₓ'. -/
theorem smul_pi₀ [GroupWithZero K] [∀ i, MulAction K (R i)] {r : K} (S : Set ι) (t : ∀ i, Set (R i))
    (hr : r ≠ 0) : r • S.pi t = S.pi (r • t) :=
  smul_pi (Units.mk0 r hr) S t
#align smul_pi₀ smul_pi₀