/-
Copyright (c) 2022 María Inés de Frutos-Fernández. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: María Inés de Frutos-Fernández
-/
import ring_theory.dedekind_domain.ideal
import ring_theory.valuation.extend_to_localization
import ring_theory.valuation.valuation_subring
import ring_theory.polynomial.cyclotomic.basic
import topology.algebra.valued_field

/-!
# Adic valuations on Dedekind domains
Given a Dedekind domain `R` of Krull dimension 1 and a maximal ideal `v` of `R`, we define the
`v`-adic valuation on `R` and its extension to the field of fractions `K` of `R`.
We prove several properties of this valuation, including the existence of uniformizers.

We define the completion of `K` with respect to the `v`-adic valuation, denoted
`v.adic_completion`,and its ring of integers, denoted `v.adic_completion_integers`.

## Main definitions
 - `is_dedekind_domain.height_one_spectrum.int_valuation v` is the `v`-adic valuation on `R`.
 - `is_dedekind_domain.height_one_spectrum.valuation v` is the `v`-adic valuation on `K`.
 - `is_dedekind_domain.height_one_spectrum.adic_completion v` is the completion of `K` with respect
    to its `v`-adic valuation.
 - `is_dedekind_domain.height_one_spectrum.adic_completion_integers v` is the ring of integers of
    `v.adic_completion`.

## Main results
- `is_dedekind_domain.height_one_spectrum.int_valuation_le_one` : The `v`-adic valuation on `R` is
  bounded above by 1.
- `is_dedekind_domain.height_one_spectrum.int_valuation_lt_one_iff_dvd` : The `v`-adic valuation of
  `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`.
- `is_dedekind_domain.height_one_spectrum.int_valuation_le_pow_iff_dvd` : The `v`-adic valuation of
  `r ∈ R` is less than or equal to `multiplicative.of_add (-n)` if and only if `vⁿ` divides the
  ideal `(r)`.
- `is_dedekind_domain.height_one_spectrum.int_valuation_exists_uniformizer` : There exists `π ∈ R`
  with `v`-adic valuation `multiplicative.of_add (-1)`.
- `is_dedekind_domain.height_one_spectrum.valuation_of_mk'` : The `v`-adic valuation of `r/s ∈ K`
  is the valuation of `r` divided by the valuation of `s`.
- `is_dedekind_domain.height_one_spectrum.valuation_of_algebra_map` : The `v`-adic valuation on `K`
  extends the `v`-adic valuation on `R`.
- `is_dedekind_domain.height_one_spectrum.valuation_exists_uniformizer` : There exists `π ∈ K` with
  `v`-adic valuation `multiplicative.of_add (-1)`.

## Implementation notes
We are only interested in Dedekind domains with Krull dimension 1.

## References
* [G. J. Janusz, *Algebraic Number Fields*][janusz1996]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]

## Tags
dedekind domain, dedekind ring, adic valuation
-/

noncomputable theory
open_locale classical discrete_valuation

open multiplicative is_dedekind_domain

variables {R : Type*} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type*} [field K]
  [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R)

namespace is_dedekind_domain.height_one_spectrum
/-! ### Adic valuations on the Dedekind domain R -/

/-- The additive `v`-adic valuation of `r ∈ R` is the exponent of `v` in the factorization of the
ideal `(r)`, if `r` is nonzero, or infinity, if `r = 0`. `int_valuation_def` is the corresponding
multiplicative valuation. -/
def int_valuation_def (r : R) : ℤₘ₀ :=
if r = 0 then 0 else multiplicative.of_add
  (-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ)

lemma int_valuation_def_if_pos {r : R} (hr : r = 0) : v.int_valuation_def r = 0 := if_pos hr

lemma int_valuation_def_if_neg {r : R} (hr : r ≠ 0) : v.int_valuation_def r = (multiplicative.of_add
  (-(associates.mk v.as_ideal).count (associates.mk (ideal.span {r} : ideal R)).factors : ℤ)) :=
if_neg hr

/-- Nonzero elements have nonzero adic valuation. -/
lemma int_valuation_ne_zero (x : R) (hx : x ≠ 0) : v.int_valuation_def x ≠ 0 :=
begin
  rw [int_valuation_def, if_neg hx],
  exact with_zero.coe_ne_zero,
end

/-- Nonzero divisors have nonzero valuation. -/
lemma int_valuation_ne_zero' (x : non_zero_divisors R) : v.int_valuation_def x ≠ 0 :=
v.int_valuation_ne_zero x (non_zero_divisors.coe_ne_zero x)

/-- Nonzero divisors have valuation greater than zero. -/
lemma int_valuation_zero_le (x : non_zero_divisors R) : 0 < v.int_valuation_def x :=
begin
  rw [v.int_valuation_def_if_neg (non_zero_divisors.coe_ne_zero x)],
  exact with_zero.zero_lt_coe _,
end

/-- The `v`-adic valuation on `R` is bounded above by 1. -/
lemma int_valuation_le_one (x : R) : v.int_valuation_def x ≤ 1 :=
begin
  rw int_valuation_def,
  by_cases hx : x = 0,
  { rw if_pos hx, exact with_zero.zero_le 1 },
  { rw [if_neg hx, ← with_zero.coe_one, ← of_add_zero, with_zero.coe_le_coe, of_add_le,
      right.neg_nonpos_iff],
    exact int.coe_nat_nonneg _ }
end

/-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/
lemma int_valuation_lt_one_iff_dvd (r : R) :
  v.int_valuation_def r < 1 ↔ v.as_ideal ∣ ideal.span {r} :=
begin
  rw int_valuation_def,
  split_ifs with hr,
  { simpa [hr] using (with_zero.zero_lt_coe _) },
  { rw [← with_zero.coe_one, ← of_add_zero, with_zero.coe_lt_coe, of_add_lt, neg_lt_zero,
      ← int.coe_nat_zero, int.coe_nat_lt, zero_lt_iff],
    have h : (ideal.span {r} : ideal R) ≠ 0,
    { rw [ne.def, ideal.zero_eq_bot, ideal.span_singleton_eq_bot],
      exact hr },
    apply associates.count_ne_zero_iff_dvd h (by apply v.irreducible) }
end

/-- The `v`-adic valuation of `r ∈ R` is less than `multiplicative.of_add (-n)` if and only if
`vⁿ` divides the ideal `(r)`. -/
lemma int_valuation_le_pow_iff_dvd (r : R) (n : ℕ) :
  v.int_valuation_def r ≤ multiplicative.of_add (-(n : ℤ)) ↔ v.as_ideal^n ∣ ideal.span {r} :=
begin
  rw int_valuation_def,
  split_ifs with hr,
  { simp_rw [hr, ideal.dvd_span_singleton, zero_le', submodule.zero_mem], },
  { rw [with_zero.coe_le_coe, of_add_le, neg_le_neg_iff, int.coe_nat_le, ideal.dvd_span_singleton,
      ← associates.le_singleton_iff, associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hr)
      (by apply v.associates_irreducible)] }
end

/-- The `v`-adic valuation of `0 : R` equals 0. -/
lemma int_valuation.map_zero' : v.int_valuation_def 0 = 0 := v.int_valuation_def_if_pos (eq.refl 0)

/-- The `v`-adic valuation of `1 : R` equals 1. -/
lemma int_valuation.map_one' : v.int_valuation_def 1 = 1 :=
by rw [v.int_valuation_def_if_neg (zero_ne_one.symm : (1 : R) ≠ 0), ideal.span_singleton_one,
  ← ideal.one_eq_top, associates.mk_one, associates.factors_one, associates.count_zero
  (by apply v.associates_irreducible), int.coe_nat_zero, neg_zero, of_add_zero, with_zero.coe_one]

/-- The `v`-adic valuation of a product equals the product of the valuations. -/
lemma int_valuation.map_mul' (x y : R) :
  v.int_valuation_def (x * y) = v.int_valuation_def x * v.int_valuation_def y :=
begin
  simp only [int_valuation_def],
  by_cases hx : x = 0,
  { rw [hx, zero_mul, if_pos (eq.refl _), zero_mul] },
  { by_cases hy : y = 0,
    { rw [hy, mul_zero, if_pos (eq.refl _), mul_zero] },
    { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_zero.coe_mul, with_zero.coe_inj,
        ← of_add_add, ← ideal.span_singleton_mul_span_singleton, ← associates.mk_mul_mk, ← neg_add,
        associates.count_mul (by apply associates.mk_ne_zero'.mpr hx)
        (by apply associates.mk_ne_zero'.mpr hy) (by apply v.associates_irreducible)],
      refl }}
end

lemma int_valuation.le_max_iff_min_le {a b c : ℕ} :  multiplicative.of_add(-c : ℤ) ≤
  max (multiplicative.of_add(-a : ℤ)) (multiplicative.of_add(-b : ℤ)) ↔ min a b ≤ c :=
by rw [le_max_iff, of_add_le, of_add_le, neg_le_neg_iff, neg_le_neg_iff, int.coe_nat_le,
    int.coe_nat_le, ← min_le_iff]

/-- The `v`-adic valuation of a sum is bounded above by the maximum of the valuations. -/
lemma int_valuation.map_add_le_max' (x y : R) : v.int_valuation_def (x + y) ≤
  max (v.int_valuation_def x) (v.int_valuation_def y) :=
begin
  by_cases hx : x = 0,
  { rw [hx, zero_add],
    conv_rhs {rw [int_valuation_def, if_pos (eq.refl _)]},
    rw max_eq_right (with_zero.zero_le (v.int_valuation_def y)),
    exact le_refl _, },
  { by_cases hy : y = 0,
    { rw [hy, add_zero],
      conv_rhs {rw [max_comm, int_valuation_def, if_pos (eq.refl _)]},
      rw max_eq_right (with_zero.zero_le (v.int_valuation_def x)),
      exact le_refl _ },
    { by_cases hxy : x + y = 0,
      { rw [int_valuation_def, if_pos hxy], exact zero_le',},
      { rw [v.int_valuation_def_if_neg hxy, v.int_valuation_def_if_neg hx,
          v.int_valuation_def_if_neg hy, with_zero.le_max_iff, int_valuation.le_max_iff_min_le],
      set nmin := min
        ((associates.mk v.as_ideal).count (associates.mk (ideal.span {x})).factors)
        ((associates.mk v.as_ideal).count (associates.mk (ideal.span {y})).factors),
      have h_dvd_x : x ∈ v.as_ideal ^ (nmin),
      { rw [← associates.le_singleton_iff x nmin _,
          associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hx) _],
        exact min_le_left _ _,
        apply v.associates_irreducible },
      have h_dvd_y : y ∈ v.as_ideal ^ nmin,
      { rw [← associates.le_singleton_iff y nmin _,
          associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hy) _],
        exact min_le_right _ _,
        apply v.associates_irreducible },
      have h_dvd_xy : associates.mk v.as_ideal^nmin ≤ associates.mk (ideal.span {x + y}),
      { rw associates.le_singleton_iff,
        exact ideal.add_mem (v.as_ideal^nmin) h_dvd_x h_dvd_y, },
      rw (associates.prime_pow_dvd_iff_le (associates.mk_ne_zero'.mpr hxy) _) at h_dvd_xy,
      exact h_dvd_xy,
      apply v.associates_irreducible, }}}
end

/-- The `v`-adic valuation on `R`. -/
def int_valuation : valuation R ℤₘ₀ :=
{ to_fun          := v.int_valuation_def,
  map_zero'       := int_valuation.map_zero' v,
  map_one'        := int_valuation.map_one' v,
  map_mul'        := int_valuation.map_mul' v,
  map_add_le_max' := int_valuation.map_add_le_max' v }

/-- There exists `π ∈ R` with `v`-adic valuation `multiplicative.of_add (-1)`. -/
lemma int_valuation_exists_uniformizer :
  ∃ (π : R), v.int_valuation_def π = multiplicative.of_add (-1 : ℤ) :=
begin
  have hv : _root_.irreducible (associates.mk v.as_ideal) := v.associates_irreducible,
  have hlt : v.as_ideal^2 < v.as_ideal,
  { rw ← ideal.dvd_not_unit_iff_lt,
    exact ⟨v.ne_bot, v.as_ideal,
     (not_congr ideal.is_unit_iff).mpr (ideal.is_prime.ne_top v.is_prime), sq v.as_ideal⟩ } ,
  obtain ⟨π, mem, nmem⟩ := set_like.exists_of_lt hlt,
  have hπ : associates.mk (ideal.span {π}) ≠ 0,
  { rw associates.mk_ne_zero',
    intro h,
    rw h at nmem,
    exact nmem (submodule.zero_mem (v.as_ideal^2)), },
  use π,
  rw [int_valuation_def, if_neg (associates.mk_ne_zero'.mp hπ), with_zero.coe_inj],
  apply congr_arg,
  rw [neg_inj, ← int.coe_nat_one, int.coe_nat_inj'],
  rw [← ideal.dvd_span_singleton, ← associates.mk_le_mk_iff_dvd_iff] at mem nmem,
  rw [← pow_one (associates.mk v.as_ideal), associates.prime_pow_dvd_iff_le hπ hv] at mem,
  rw [associates.mk_pow, associates.prime_pow_dvd_iff_le hπ hv, not_le] at nmem,
  exact nat.eq_of_le_of_lt_succ mem nmem,
end

/-! ### Adic valuations on the field of fractions `K` -/

/-- The `v`-adic valuation of `x ∈ K` is the valuation of `r` divided by the valuation of `s`,
where `r` and `s` are chosen so that `x = r/s`. -/
def valuation (v : height_one_spectrum R) : valuation K ℤₘ₀ :=
v.int_valuation.extend_to_localization (λ r hr, set.mem_compl $ v.int_valuation_ne_zero' ⟨r, hr⟩) K

lemma valuation_def (x : K) : v.valuation x = v.int_valuation.extend_to_localization
  (λ r hr, set.mem_compl (v.int_valuation_ne_zero' ⟨r, hr⟩)) K x :=
rfl

/-- The `v`-adic valuation of `r/s ∈ K` is the valuation of `r` divided by the valuation of `s`. -/
lemma valuation_of_mk' {r : R} {s : non_zero_divisors R} :
  v.valuation (is_localization.mk' K r s) = v.int_valuation r / v.int_valuation s :=
begin
  erw [valuation_def, (is_localization.to_localization_map (non_zero_divisors R) K).lift_mk',
    div_eq_mul_inv, mul_eq_mul_left_iff],
  left,
  rw [units.coe_inv, inv_inj],
  refl,
end

/-- The `v`-adic valuation on `K` extends the `v`-adic valuation on `R`. -/
lemma valuation_of_algebra_map (r : R) :
  v.valuation (algebra_map R K r) = v.int_valuation r :=
by rw [valuation_def, valuation.extend_to_localization_apply_map_apply]

/-- The `v`-adic valuation on `R` is bounded above by 1. -/
lemma valuation_le_one (r : R) : v.valuation (algebra_map R K r) ≤ 1 :=
by { rw valuation_of_algebra_map, exact v.int_valuation_le_one r }

/-- The `v`-adic valuation of `r ∈ R` is less than 1 if and only if `v` divides the ideal `(r)`. -/
lemma valuation_lt_one_iff_dvd (r : R) :
  v.valuation (algebra_map R K r) < 1 ↔ v.as_ideal ∣ ideal.span {r} :=
by { rw valuation_of_algebra_map, exact v.int_valuation_lt_one_iff_dvd r }

variable (K)
/-- There exists `π ∈ K` with `v`-adic valuation `multiplicative.of_add (-1)`. -/
lemma valuation_exists_uniformizer :
  ∃ (π : K), v.valuation π = multiplicative.of_add (-1 : ℤ) :=
begin
  obtain ⟨r, hr⟩ := v.int_valuation_exists_uniformizer,
  use algebra_map R K r,
  rw [valuation_def, valuation.extend_to_localization_apply_map_apply],
  exact hr,
end

/-- Uniformizers are nonzero. -/
lemma valuation_uniformizer_ne_zero :
  (classical.some (v.valuation_exists_uniformizer K)) ≠ 0 :=
begin
  have hu := classical.some_spec (v.valuation_exists_uniformizer K),
  exact (valuation.ne_zero_iff _).mp (ne_of_eq_of_ne hu with_zero.coe_ne_zero),
end

/-! ### Completions with respect to adic valuations

Given a Dedekind domain `R` with field of fractions `K` and a maximal ideal `v` of `R`, we define
the completion of `K` with respect to its `v`-adic valuation, denoted `v.adic_completion`, and its
ring of integers, denoted `v.adic_completion_integers`. -/

variable {K}

/-- `K` as a valued field with the `v`-adic valuation. -/
def adic_valued : valued K ℤₘ₀ := valued.mk' v.valuation

lemma adic_valued_apply {x : K} : (v.adic_valued.v : _) x = v.valuation x := rfl

variables (K)

/-- The completion of `K` with respect to its `v`-adic valuation. -/
def adic_completion := @uniform_space.completion K v.adic_valued.to_uniform_space

instance : field (v.adic_completion K) :=
@uniform_space.completion.field K _ v.adic_valued.to_uniform_space _ _
  v.adic_valued.to_uniform_add_group

instance : inhabited (v.adic_completion K) := ⟨0⟩

instance valued_adic_completion : valued (v.adic_completion K) ℤₘ₀ :=
@valued.valued_completion _ _ _ _ v.adic_valued

lemma valued_adic_completion_def {x : v.adic_completion K} :
  valued.v x = @valued.extension K _ _ _ (adic_valued v) x := rfl

instance adic_completion_complete_space : complete_space (v.adic_completion K) :=
@uniform_space.completion.complete_space K v.adic_valued.to_uniform_space

instance adic_completion.has_lift_t : has_lift_t K (v.adic_completion K) :=
(infer_instance : has_lift_t K (@uniform_space.completion K v.adic_valued.to_uniform_space))

/-- The ring of integers of `adic_completion`. -/
def adic_completion_integers : valuation_subring (v.adic_completion K) := valued.v.valuation_subring

instance : inhabited (adic_completion_integers K v) := ⟨0⟩

variables (R K)

lemma mem_adic_completion_integers {x : v.adic_completion K} :
  x ∈ v.adic_completion_integers K ↔ (valued.v x : ℤₘ₀) ≤ 1 :=
iff.rfl

section algebra_instances

@[priority 100] instance adic_valued.has_uniform_continuous_const_smul' :
  @has_uniform_continuous_const_smul R K v.adic_valued.to_uniform_space _ :=
@has_uniform_continuous_const_smul_of_continuous_const_smul R K _ _ _
    v.adic_valued.to_uniform_space _ _

instance adic_valued.has_uniform_continuous_const_smul :
  @has_uniform_continuous_const_smul K K v.adic_valued.to_uniform_space _ :=
@ring.has_uniform_continuous_const_smul K _ v.adic_valued.to_uniform_space _ _

instance adic_completion.algebra' : algebra R (v.adic_completion K) :=
@uniform_space.completion.algebra K _ v.adic_valued.to_uniform_space _ _ R _ _
  (adic_valued.has_uniform_continuous_const_smul' R K v)

@[simp] lemma coe_smul_adic_completion (r : R) (x : K) :
  (↑(r • x) : v.adic_completion K) = r • (↑x : v.adic_completion K) :=
@uniform_space.completion.coe_smul R K v.adic_valued.to_uniform_space _ _ r x

instance : algebra K (v.adic_completion K) :=
@uniform_space.completion.algebra' K _ v.adic_valued.to_uniform_space _ _

lemma algebra_map_adic_completion' :
  ⇑(algebra_map R $ v.adic_completion K) = coe ∘ algebra_map R K :=
rfl

lemma algebra_map_adic_completion :
  ⇑(algebra_map K $ v.adic_completion K) = coe :=
rfl

instance : is_scalar_tower R K (v.adic_completion K) :=
@uniform_space.completion.is_scalar_tower R K K v.adic_valued.to_uniform_space _ _ _
  (adic_valued.has_uniform_continuous_const_smul' R K v) _ _

instance : algebra R (v.adic_completion_integers K) :=
{ smul      := λ r x, ⟨r • (x : v.adic_completion K), begin
    have h : ((algebra_map R (adic_completion K v)) r) = (coe $ algebra_map R K r) := rfl,
    rw algebra.smul_def,
    refine valuation_subring.mul_mem _ _ _ _ x.2,
    rw [mem_adic_completion_integers, h, valued.valued_completion_apply],
    exact v.valuation_le_one _,
  end⟩,
  to_fun    := λ r, ⟨coe $ algebra_map R K r, by simpa only [mem_adic_completion_integers,
    valued.valued_completion_apply] using v.valuation_le_one _⟩,
  map_one'  := by simp only [map_one]; refl,
  map_mul'  := λ x y,
  begin
    ext,
    simp_rw [ring_hom.map_mul, subring.coe_mul, subtype.coe_mk, uniform_space.completion.coe_mul],
  end,
  map_zero' := by simp only [map_zero]; refl,
  map_add'  := λ x y,
  begin
    ext,
    simp_rw [ring_hom.map_add, subring.coe_add, subtype.coe_mk, uniform_space.completion.coe_add],
  end,
  commutes' := λ r x, by rw mul_comm,
  smul_def' := λ r x, begin
    ext,
    simp only [subring.coe_mul, set_like.coe_mk, algebra.smul_def],
    refl,
  end }

@[simp] lemma coe_smul_adic_completion_integers (r : R) (x : v.adic_completion_integers K) :
  (↑(r • x) : v.adic_completion K) = r • (x : v.adic_completion K) :=
rfl

instance : no_zero_smul_divisors R (v.adic_completion_integers K) :=
{ eq_zero_or_eq_zero_of_smul_eq_zero := λ c x hcx,
  begin
    rw [algebra.smul_def, mul_eq_zero] at hcx,
    refine hcx.imp_left (λ hc, _),
    letI : uniform_space K := v.adic_valued.to_uniform_space,
    rw ← map_zero (algebra_map R (v.adic_completion_integers K)) at hc,
    exact (is_fraction_ring.injective R K
      (uniform_space.completion.coe_injective K (subtype.ext_iff.mp hc)))
  end }

instance adic_completion.is_scalar_tower' :
  is_scalar_tower R (v.adic_completion_integers K) (v.adic_completion K) :=
{ smul_assoc := λ x y z, by {simp only [algebra.smul_def], apply mul_assoc, }}

end algebra_instances

end is_dedekind_domain.height_one_spectrum


/-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.localization
import ring_theory.noetherian
import ring_theory.principal_ideal_domain
import tactic.field_simp

/-!
# Fractional ideals

This file defines fractional ideals of an integral domain and proves basic facts about them.

## Main definitions
Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the
natural ring hom from `R` to `P`.
 * `is_fractional` defines which `R`-submodules of `P` are fractional ideals
 * `fractional_ideal S P` is the type of fractional ideals in `P`
 * `has_coe_t (ideal R) (fractional_ideal S P)` instance
 * `comm_semiring (fractional_ideal S P)` instance:
   the typical ideal operations generalized to fractional ideals
 * `lattice (fractional_ideal S P)` instance
 * `map` is the pushforward of a fractional ideal along an algebra morphism

Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions).
 * `fractional_ideal R⁰ K` is the type of fractional ideals in the field of fractions
 * `has_div (fractional_ideal R⁰ K)` instance:
   the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined)

## Main statements

  * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone
  * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists
  * `is_noetherian` states that very fractional ideal of a noetherian integral domain is noetherian

## Implementation notes

Fractional ideals are considered equal when they contain the same elements,
independent of the denominator `a : R` such that `a I ⊆ R`.
Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`,
instead of having `fractional_ideal` be a structure of which `a` is a field.

Most definitions in this file specialize operations from submodules to fractional ideals,
proving that the result of this operation is fractional if the input is fractional.
Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`,
in order to re-use their respective proof terms.
We can still use `simp` to show `↑I + ↑J = ↑(I + J)` and `↑⊥ = ↑0`.

Many results in fact do not need that `P` is a localization, only that `P` is an
`R`-algebra. We omit the `is_localization` parameter whenever this is practical.
Similarly, we don't assume that the localization is a field until we need it to
define ideal quotients. When this assumption is needed, we replace `S` with `R⁰`,
making the localization a field.

## References

  * https://en.wikipedia.org/wiki/Fractional_ideal

## Tags

fractional ideal, fractional ideals, invertible ideal
-/

open is_localization
open_locale pointwise

open_locale non_zero_divisors

section defs

variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P]
variables [algebra R P]

variables (S)

/-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/
def is_fractional (I : submodule R P) :=
∃ a ∈ S, ∀ b ∈ I, is_integer R (a • b)

variables (S P)

/-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`.

  More precisely, let `P` be a localization of `R` at some submonoid `S`,
  then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`,
  such that there is a nonzero `a : R` with `a I ⊆ R`.
-/
def fractional_ideal :=
{I : submodule R P // is_fractional S I}

end defs

namespace fractional_ideal

open set
open submodule

variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P]
variables [algebra R P] [loc : is_localization S P]

/-- Map a fractional ideal `I` to a submodule by forgetting that `∃ a, a I ⊆ R`.

This coercion is typically called `coe_to_submodule` in lemma names
(or `coe` when the coercion is clear from the context),
not to be confused with `is_localization.coe_submodule : ideal R → submodule R P`
(which we use to define `coe : ideal R → fractional_ideal S P`,
referred to as `coe_ideal` in theorem names).
-/
instance : has_coe (fractional_ideal S P) (submodule R P) := ⟨λ I, I.val⟩

protected lemma is_fractional (I : fractional_ideal S P) :
  is_fractional S (I : submodule R P) :=
I.prop

section set_like

instance : set_like (fractional_ideal S P) P :=
{ coe := λ I, ↑(I : submodule R P),
  coe_injective' := set_like.coe_injective.comp subtype.coe_injective }

@[simp] lemma mem_coe {I : fractional_ideal S P} {x : P} :
  x ∈ (I : submodule R P) ↔ x ∈ I :=
iff.rfl

@[ext] lemma ext {I J : fractional_ideal S P} : (∀ x, x ∈ I ↔ x ∈ J) → I = J := set_like.ext

/-- Copy of a `fractional_ideal` with a new underlying set equal to the old one.
Useful to fix definitional equalities. -/
protected def copy (p : fractional_ideal S P) (s : set P) (hs : s = ↑p) : fractional_ideal S P :=
⟨submodule.copy p s hs, by { convert p.is_fractional, ext, simp only [hs], refl }⟩

end set_like

@[simp] lemma val_eq_coe (I : fractional_ideal S P) : I.val = I := rfl

@[simp, norm_cast] lemma coe_mk (I : submodule R P) (hI : is_fractional S I) :
  (subtype.mk I hI : submodule R P) = I := rfl

lemma coe_to_submodule_injective :
  function.injective (coe : fractional_ideal S P → submodule R P) :=
subtype.coe_injective

lemma is_fractional_of_le_one (I : submodule R P) (h : I ≤ 1) :
  is_fractional S I :=
begin
  use [1, S.one_mem],
  intros b hb,
  rw one_smul,
  obtain ⟨b', b'_mem, rfl⟩ := h hb,
  exact set.mem_range_self b',
end

lemma is_fractional_of_le {I : submodule R P} {J : fractional_ideal S P}
  (hIJ : I ≤ J) : is_fractional S I :=
begin
  obtain ⟨a, a_mem, ha⟩ := J.is_fractional,
  use [a, a_mem],
  intros b b_mem,
  exact ha b (hIJ b_mem)
end

/-- Map an ideal `I` to a fractional ideal by forgetting `I` is integral.

This is a bundled version of `is_localization.coe_submodule : ideal R → submodule R P`,
which is not to be confused with the `coe : fractional_ideal S P → submodule R P`,
also called `coe_to_submodule` in theorem names.

This map is available as a ring hom, called `fractional_ideal.coe_ideal_hom`.
-/
-- Is a `coe_t` rather than `coe` to speed up failing inference, see library note [use has_coe_t]
instance coe_to_fractional_ideal : has_coe_t (ideal R) (fractional_ideal S P) :=
⟨λ I, ⟨coe_submodule P I, is_fractional_of_le_one _
  (by simpa using coe_submodule_mono P (le_top : I ≤ ⊤))⟩⟩

@[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) :
  ((I : fractional_ideal S P) : submodule R P) = coe_submodule P I := rfl

variables (S)

@[simp] lemma mem_coe_ideal {x : P} {I : ideal R} :
  x ∈ (I : fractional_ideal S P) ↔ ∃ x', x' ∈ I ∧ algebra_map R P x' = x :=
mem_coe_submodule _ _

lemma mem_coe_ideal_of_mem {x : R} {I : ideal R} (hx : x ∈ I) :
  algebra_map R P x ∈ (I : fractional_ideal S P) :=
(mem_coe_ideal S).mpr ⟨x, hx, rfl⟩

lemma coe_ideal_le_coe_ideal' [is_localization S P] (h : S ≤ non_zero_divisors R)
  {I J : ideal R} : (I : fractional_ideal S P) ≤ J ↔ I ≤ J :=
coe_submodule_le_coe_submodule h

@[simp] lemma coe_ideal_le_coe_ideal (K : Type*) [comm_ring K] [algebra R K] [is_fraction_ring R K]
  {I J : ideal R} : (I : fractional_ideal R⁰ K) ≤ J ↔ I ≤ J :=
is_fraction_ring.coe_submodule_le_coe_submodule

instance : has_zero (fractional_ideal S P) := ⟨(0 : ideal R)⟩

@[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal S P) ↔ x = 0 :=
⟨(λ ⟨x', x'_mem_zero, x'_eq_x⟩,
   have x'_eq_zero : x' = 0 := x'_mem_zero,
   by simp [x'_eq_x.symm, x'_eq_zero]),
 (λ hx, ⟨0, rfl, by simp [hx]⟩)⟩

variables {S}

@[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal S P) = (⊥ : submodule R P) :=
submodule.ext $ λ _, mem_zero_iff S

@[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal S P) = 0 :=
rfl

variables (P)

include loc

@[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) :
  (∃ x', x' ∈ I ∧ algebra_map R P x' = algebra_map R P x) ↔ x ∈ I :=
⟨λ ⟨x', hx', eq⟩, is_localization.injective _ h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩

variables {P}

lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) :
  function.injective (coe : ideal R → fractional_ideal S P) :=
λ I J heq, have
  ∀ (x : R), algebra_map R P x ∈ (I : fractional_ideal S P) ↔
             algebra_map R P x ∈ (J : fractional_ideal S P) :=
λ x, heq ▸ iff.rfl,
ideal.ext (by simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq P h] using this)

lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) :
  (I : fractional_ideal S P) = 0 ↔ I = (⊥ : ideal R) :=
⟨λ h, coe_to_fractional_ideal_injective hS h,
 λ h, by rw [h, coe_to_fractional_ideal_bot]⟩

lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) :
  (I : fractional_ideal S P) ≠ 0 ↔ I ≠ (⊥ : ideal R) :=
not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS)

omit loc

lemma coe_to_submodule_eq_bot {I : fractional_ideal S P} :
  (I : submodule R P) = ⊥ ↔ I = 0 :=
⟨λ h, coe_to_submodule_injective (by simp [h]),
 λ h, by simp [h]⟩

lemma coe_to_submodule_ne_bot {I : fractional_ideal S P} :
  ↑I ≠ (⊥ : submodule R P) ↔ I ≠ 0 :=
not_iff_not.mpr coe_to_submodule_eq_bot

instance : inhabited (fractional_ideal S P) := ⟨0⟩

instance : has_one (fractional_ideal S P) :=
⟨(⊤ : ideal R)⟩

variables (S)

@[simp, norm_cast] lemma coe_ideal_top : ((⊤ : ideal R) : fractional_ideal S P) = 1 :=
rfl

lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal S P) ↔ ∃ x' : R, algebra_map R P x' = x :=
iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨⟩, h⟩)

lemma coe_mem_one (x : R) : algebra_map R P x ∈ (1 : fractional_ideal S P) :=
(mem_one_iff S).mpr ⟨x, rfl⟩

lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal S P) :=
(mem_one_iff S).mpr ⟨1, ring_hom.map_one _⟩

variables {S}

/-- `(1 : fractional_ideal S P)` is defined as the R-submodule `f(R) ≤ P`.

However, this is not definitionally equal to `1 : submodule R P`,
which is proved in the actual `simp` lemma `coe_one`. -/
lemma coe_one_eq_coe_submodule_top :
  ↑(1 : fractional_ideal S P) = coe_submodule P (⊤ : ideal R) :=
rfl

@[simp, norm_cast] lemma coe_one :
  (↑(1 : fractional_ideal S P) : submodule R P) = 1 :=
by rw [coe_one_eq_coe_submodule_top, coe_submodule_top]

section lattice

/-!
### `lattice` section

Defines the order on fractional ideals as inclusion of their underlying sets,
and ports the lattice structure on submodules to fractional ideals.
-/

@[simp] lemma coe_le_coe {I J : fractional_ideal S P} :
  (I : submodule R P) ≤ (J : submodule R P) ↔ I ≤ J :=
iff.rfl

lemma zero_le (I : fractional_ideal S P) : 0 ≤ I :=
begin
  intros x hx,
  convert submodule.zero_mem _,
  simpa using hx
end

instance order_bot : order_bot (fractional_ideal S P) :=
{ bot := 0,
  bot_le := zero_le }

@[simp] lemma bot_eq_zero : (⊥ : fractional_ideal S P) = 0 :=
rfl

@[simp] lemma le_zero_iff {I : fractional_ideal S P} : I ≤ 0 ↔ I = 0 :=
le_bot_iff

lemma eq_zero_iff {I : fractional_ideal S P} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) :=
⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx),
  (λ h, le_bot_iff.mp (λ x hx, (mem_zero_iff S).mpr (h x hx))) ⟩

lemma fractional_sup (I J : fractional_ideal S P) : is_fractional S (I ⊔ J : submodule R P) :=
begin
  rcases I.is_fractional with ⟨aI, haI, hI⟩,
  rcases J.is_fractional with ⟨aJ, haJ, hJ⟩,
  use aI * aJ,
  use S.mul_mem haI haJ,
  intros b hb,
  rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, rfl⟩,
  rw smul_add,
  apply is_integer_add,
  { rw [mul_smul, smul_comm],
    exact is_integer_smul (hI bI hbI), },
  { rw mul_smul,
    exact is_integer_smul (hJ bJ hbJ) }
end

lemma fractional_inf (I J : fractional_ideal S P) : is_fractional S (I ⊓ J : submodule R P) :=
begin
  rcases I.is_fractional with ⟨aI, haI, hI⟩,
  use aI,
  use haI,
  intros b hb,
  rcases mem_inf.mp hb with ⟨hbI, hbJ⟩,
  exact hI b hbI
end

instance lattice : lattice (fractional_ideal S P) :=
{ inf := λ I J, ⟨I ⊓ J, fractional_inf I J⟩,
  sup := λ I J, ⟨I ⊔ J, fractional_sup I J⟩,
  inf_le_left := λ I J, show (I ⊓ J : submodule R P) ≤ I, from inf_le_left,
  inf_le_right := λ I J, show (I ⊓ J : submodule R P) ≤ J, from inf_le_right,
  le_inf := λ I J K hIJ hIK, show (I : submodule R P) ≤ J ⊓ K, from le_inf hIJ hIK,
  le_sup_left := λ I J, show (I : submodule R P) ≤ I ⊔ J, from le_sup_left,
  le_sup_right := λ I J, show (J : submodule R P) ≤ I ⊔ J, from le_sup_right,
  sup_le := λ I J K hIK hJK, show (I ⊔ J : submodule R P) ≤ K, from sup_le hIK hJK,
  ..set_like.partial_order }

instance : semilattice_sup (fractional_ideal S P) :=
{ ..fractional_ideal.lattice }

end lattice

section semiring

instance : has_add (fractional_ideal S P) := ⟨(⊔)⟩

@[simp]
lemma sup_eq_add (I J : fractional_ideal S P) : I ⊔ J = I + J := rfl

@[simp, norm_cast]
lemma coe_add (I J : fractional_ideal S P) : (↑(I + J) : submodule R P) = I + J := rfl

@[simp, norm_cast]
lemma coe_ideal_sup (I J : ideal R) : ↑(I ⊔ J) = (I + J : fractional_ideal S P) :=
coe_to_submodule_injective $ coe_submodule_sup _ _ _

lemma fractional_mul (I J : fractional_ideal S P) : is_fractional S (I * J : submodule R P) :=
begin
  rcases I with ⟨I, aI, haI, hI⟩,
  rcases J with ⟨J, aJ, haJ, hJ⟩,
  use aI * aJ,
  use S.mul_mem haI haJ,
  intros b hb,
  apply submodule.mul_induction_on hb,
  { intros m hm n hn,
    obtain ⟨n', hn'⟩ := hJ n hn,
    rw [mul_smul, mul_comm m, ← smul_mul_assoc, ← hn', ← algebra.smul_def],
    apply hI,
    exact submodule.smul_mem _ _ hm },
  { rw smul_zero,
    exact ⟨0, ring_hom.map_zero _⟩ },
  { intros x y hx hy,
    rw smul_add,
    apply is_integer_add hx hy },
  { intros r x hx,
    rw smul_comm,
    exact is_integer_smul hx },
end

/-- `fractional_ideal.mul` is the product of two fractional ideals,
used to define the `has_mul` instance.

This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`.

Elaborated terms involving `fractional_ideal` tend to grow quite large,
so by making definitions irreducible, we hope to avoid deep unfolds.
-/
@[irreducible]
def mul (I J : fractional_ideal S P) : fractional_ideal S P :=
⟨I * J, fractional_mul I J⟩

local attribute [semireducible] mul

instance : has_mul (fractional_ideal S P) := ⟨λ I J, mul I J⟩

@[simp] lemma mul_eq_mul (I J : fractional_ideal S P) : mul I J = I * J := rfl

@[simp, norm_cast]
lemma coe_mul (I J : fractional_ideal S P) : (↑(I * J) : submodule R P) = I * J := rfl

@[simp, norm_cast]
lemma coe_ideal_mul (I J : ideal R) : (↑(I * J) : fractional_ideal S P) = I * J :=
coe_to_submodule_injective $ coe_submodule_mul _ _ _

lemma mul_left_mono (I : fractional_ideal S P) : monotone ((*) I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy))

lemma mul_right_mono (I : fractional_ideal S P) : monotone (λ J, J * I) :=
λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy)

lemma mul_mem_mul {I J : fractional_ideal S P} {i j : P} (hi : i ∈ I) (hj : j ∈ J) :
  i * j ∈ I * J := submodule.mul_mem_mul hi hj

lemma mul_le {I J K : fractional_ideal S P} :
  I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) :=
submodule.mul_le

@[elab_as_eliminator] protected theorem mul_induction_on
  {I J : fractional_ideal S P}
  {C : P → Prop} {r : P} (hr : r ∈ I * J)
  (hm : ∀ (i ∈ I) (j ∈ J), C (i * j))
  (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y))
  (hs : ∀ (r : R) x, C x → C (r • x)) : C r :=
submodule.mul_induction_on hr hm h0 ha hs

instance comm_semiring : comm_semiring (fractional_ideal S P) :=
{ add_assoc := λ I J K, sup_assoc,
  add_comm := λ I J, sup_comm,
  add_zero := λ I, sup_bot_eq,
  zero_add := λ I, bot_sup_eq,
  mul_assoc := λ I J K, coe_to_submodule_injective (submodule.mul_assoc _ _ _),
  mul_comm := λ I J, coe_to_submodule_injective (submodule.mul_comm _ _),
  mul_one := λ I, begin
    ext,
    split; intro h,
    { apply mul_le.mpr _ h,
      rintros x hx y ⟨y', y'_mem_R, rfl⟩,
      convert submodule.smul_mem _ y' hx,
      rw [mul_comm, eq_comm],
      exact algebra.smul_def y' x },
    { have : x * 1 ∈ (I * 1) := mul_mem_mul h (one_mem_one _),
      rwa [mul_one] at this }
  end,
  one_mul := λ I, begin
    ext,
    split; intro h,
    { apply mul_le.mpr _ h,
      rintros x ⟨x', x'_mem_R, rfl⟩ y hy,
      convert submodule.smul_mem _ x' hy,
      rw eq_comm,
      exact algebra.smul_def x' y },
    { have : 1 * x ∈ (1 * I) := mul_mem_mul (one_mem_one _) h,
      rwa one_mul at this }
  end,
  mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
    (λ x hx y hy, by simp [(mem_zero_iff S).mp hy])
    rfl
    (λ x y hx hy, by simp [hx, hy])
    (λ r x hx, by simp [hx])),
  zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx
    (λ x hx y hy, by simp [(mem_zero_iff S).mp hx])
    rfl
    (λ x y hx hy, by simp [hx, hy])
    (λ r x hx, by simp [hx])),
  left_distrib := λ I J K, coe_to_submodule_injective (mul_add _ _ _),
  right_distrib := λ I J K, coe_to_submodule_injective (add_mul _ _ _),
  ..fractional_ideal.has_zero S,
  ..fractional_ideal.has_add,
  ..fractional_ideal.has_one,
  ..fractional_ideal.has_mul }

section order

lemma add_le_add_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) :
  J' + I ≤ J' + J :=
sup_le_sup_left hIJ J'

lemma mul_le_mul_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) :
  J' * I ≤ J' * J :=
mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj))

lemma le_self_mul_self {I : fractional_ideal S P} (hI: 1 ≤ I) : I ≤ I * I :=
begin
  convert mul_left_mono I hI,
  exact (mul_one I).symm
end

lemma mul_self_le_self {I : fractional_ideal S P} (hI: I ≤ 1) : I * I ≤ I :=
begin
  convert mul_left_mono I hI,
  exact (mul_one I).symm
end

lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal S P) ≤ 1 :=
λ x hx, let ⟨y, _, hy⟩ := (fractional_ideal.mem_coe_ideal S).mp hx
  in (fractional_ideal.mem_one_iff S).mpr ⟨y, hy⟩

lemma le_one_iff_exists_coe_ideal {J : fractional_ideal S P} :
  J ≤ (1 : fractional_ideal S P) ↔ ∃ (I : ideal R), ↑I = J :=
begin
  split,
  { intro hJ,
    refine ⟨⟨{x : R | algebra_map R P x ∈ J}, _, _, _⟩, _⟩,
    { rw [mem_set_of_eq, ring_hom.map_zero],
      exact J.val.zero_mem },
    { intros a b ha hb,
      rw [mem_set_of_eq, ring_hom.map_add],
      exact J.val.add_mem ha hb },
    { intros c x hx,
      rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul, ← algebra.smul_def],
      exact J.val.smul_mem c hx },
    { ext x,
      split,
      { rintros ⟨y, hy, eq_y⟩,
        rwa ← eq_y },
      { intro hx,
        obtain ⟨y, eq_x⟩ := (fractional_ideal.mem_one_iff S).mp (hJ hx),
        rw ← eq_x at *,
        exact ⟨y, hx, rfl⟩ } } },
  { rintro ⟨I, hI⟩,
    rw ← hI,
    apply coe_ideal_le_one },
end

variables (S P)

/-- `coe_ideal_hom (S : submonoid R) P` is `coe : ideal R → fractional_ideal S P` as a ring hom -/
@[simps]
def coe_ideal_hom : ideal R →+* fractional_ideal S P :=
{ to_fun := coe,
  map_add' := coe_ideal_sup,
  map_mul' := coe_ideal_mul,
  map_one' := by rw [ideal.one_eq_top, coe_ideal_top],
  map_zero' := coe_to_fractional_ideal_bot }

end order

variables {P' : Type*} [comm_ring P'] [algebra R P'] [loc' : is_localization S P']
variables {P'' : Type*} [comm_ring P''] [algebra R P''] [loc'' : is_localization S P'']

lemma fractional_map (g : P →ₐ[R] P') (I : fractional_ideal S P) :
  is_fractional S (submodule.map g.to_linear_map I) :=
begin
  rcases I with ⟨I, a, a_nonzero, hI⟩,
  use [a, a_nonzero],
  intros b hb,
  obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb,
  obtain ⟨x, hx⟩ := hI b' b'_mem,
  use x,
  erw [←g.commutes, hx, g.map_smul, hb']
end

/-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/
def map (g : P →ₐ[R] P') :
  fractional_ideal S P → fractional_ideal S P' :=
λ I, ⟨submodule.map g.to_linear_map I, fractional_map g I⟩

@[simp, norm_cast] lemma coe_map (g : P →ₐ[R] P') (I : fractional_ideal S P) :
  ↑(map g I) = submodule.map g.to_linear_map I := rfl

@[simp] lemma mem_map {I : fractional_ideal S P} {g : P →ₐ[R] P'}
  {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y :=
submodule.mem_map

variables (I J : fractional_ideal S P) (g : P →ₐ[R] P')

@[simp] lemma map_id : I.map (alg_hom.id _ _) = I :=
coe_to_submodule_injective (submodule.map_id I)

@[simp] lemma map_comp (g' : P' →ₐ[R] P'') :
  I.map (g'.comp g) = (I.map g).map g' :=
coe_to_submodule_injective (submodule.map_comp g.to_linear_map g'.to_linear_map I)

@[simp, norm_cast] lemma map_coe_ideal (I : ideal R) :
  (I : fractional_ideal S P).map g = I :=
begin
  ext x,
  simp only [mem_coe_ideal],
  split,
  { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩,
    exact ⟨y, hy, (g.commutes y).symm⟩ },
  { rintro ⟨y, hy, rfl⟩,
    exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ },
end

@[simp] lemma map_one :
  (1 : fractional_ideal S P).map g = 1 :=
map_coe_ideal g ⊤

@[simp] lemma map_zero :
  (0 : fractional_ideal S P).map g = 0 :=
map_coe_ideal g 0

@[simp] lemma map_add : (I + J).map g = I.map g + J.map g :=
coe_to_submodule_injective (submodule.map_sup _ _ _)

@[simp] lemma map_mul : (I * J).map g = I.map g * J.map g :=
coe_to_submodule_injective (submodule.map_mul _ _ _)

@[simp] lemma map_map_symm (g : P ≃ₐ[R] P') :
  (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I :=
by rw [←map_comp, g.symm_comp, map_id]

@[simp] lemma map_symm_map (I : fractional_ideal S P') (g : P ≃ₐ[R] P') :
  (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I :=
by rw [←map_comp, g.comp_symm, map_id]

lemma map_mem_map {f : P →ₐ[R] P'} (h : function.injective f) {x : P} {I : fractional_ideal S P} :
  f x ∈ map f I ↔ x ∈ I :=
mem_map.trans ⟨λ ⟨x', hx', x'_eq⟩, h x'_eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩

lemma map_injective (f : P →ₐ[R] P') (h : function.injective f) :
  function.injective (map f : fractional_ideal S P → fractional_ideal S P') :=
λ I J hIJ, fractional_ideal.ext (λ x, (fractional_ideal.map_mem_map h).symm.trans
  (hIJ.symm ▸ fractional_ideal.map_mem_map h))

/-- If `g` is an equivalence, `map g` is an isomorphism -/
def map_equiv (g : P ≃ₐ[R] P') :
  fractional_ideal S P ≃+* fractional_ideal S P' :=
{ to_fun := map g,
  inv_fun := map g.symm,
  map_add' := λ I J, map_add I J _,
  map_mul' := λ I J, map_mul I J _,
  left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] },
  right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } }

@[simp] lemma coe_fun_map_equiv (g : P ≃ₐ[R] P') :
  (map_equiv g : fractional_ideal S P → fractional_ideal S P') = map g :=
rfl

@[simp] lemma map_equiv_apply (g : P ≃ₐ[R] P') (I : fractional_ideal S P) :
  map_equiv g I = map ↑g I := rfl

@[simp] lemma map_equiv_symm (g : P ≃ₐ[R] P') :
  ((map_equiv g).symm : fractional_ideal S P' ≃+* _) = map_equiv g.symm := rfl

@[simp] lemma map_equiv_refl :
  map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal S P) :=
ring_equiv.ext (λ x, by simp)

lemma is_fractional_span_iff {s : set P} :
  is_fractional S (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → is_integer R (a • b) :=
⟨λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩,
 λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb
   h
   (by { rw smul_zero, exact is_integer_zero })
   (λ x y hx hy, by { rw smul_add, exact is_integer_add hx hy })
   (λ s x hx, by { rw smul_comm, exact is_integer_smul hx })⟩⟩

include loc

lemma is_fractional_of_fg {I : submodule R P} (hI : I.fg) :
  is_fractional S I :=
begin
  rcases hI with ⟨I, rfl⟩,
  rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩,
  rw is_fractional_span_iff,
  exact ⟨s, hs1, hs⟩,
end

omit loc

lemma mem_span_mul_finite_of_mem_mul {I J : fractional_ideal S P} {x : P} (hx : x ∈ I * J) :
  ∃ (T T' : finset P), (T : set P) ⊆ I ∧ (T' : set P) ⊆ J ∧ x ∈ span R (T * T' : set P) :=
submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx)

variables (S)

lemma coe_ideal_fg (inj : function.injective (algebra_map R P)) (I : ideal R) :
  fg ((I : fractional_ideal S P) : submodule R P) ↔ fg I :=
coe_submodule_fg _ inj _

variables {S}

lemma fg_unit (I : units (fractional_ideal S P)) :
  fg (I : submodule R P) :=
begin
  have : (1 : P) ∈ (I * ↑I⁻¹ : fractional_ideal S P),
  { rw units.mul_inv, exact one_mem_one _ },
  obtain ⟨T, T', hT, hT', one_mem⟩ := mem_span_mul_finite_of_mem_mul this,
  refine ⟨T, submodule.span_eq_of_le _ hT _⟩,
  rw [← one_mul ↑I, ← mul_one (span R ↑T)],
  conv_rhs { rw [← fractional_ideal.coe_one, ← units.mul_inv I, fractional_ideal.coe_mul,
                 mul_comm ↑↑I, ← mul_assoc] },
  refine submodule.mul_le_mul_left
    (le_trans _ (submodule.mul_le_mul_right (submodule.span_le.mpr hT'))),
  rwa [submodule.one_le, submodule.span_mul_span]
end

lemma fg_of_is_unit (I : fractional_ideal S P) (h : is_unit I) :
  fg (I : submodule R P) :=
by { rcases h with ⟨I, rfl⟩, exact fg_unit I }

lemma _root_.ideal.fg_of_is_unit (inj : function.injective (algebra_map R P))
  (I : ideal R) (h : is_unit (I : fractional_ideal S P)) :
  I.fg :=
by { rw ← coe_ideal_fg S inj I, exact fg_of_is_unit I h }

variables (S P P')

include loc loc'

/-- `canonical_equiv f f'` is the canonical equivalence between the fractional
ideals in `P` and in `P'` -/
@[irreducible]
noncomputable def canonical_equiv :
  fractional_ideal S P ≃+* fractional_ideal S P' :=
map_equiv
  { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _,
    ..ring_equiv_of_ring_equiv P P' (ring_equiv.refl R)
      (show S.map _ = S, by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) }

@[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal S P} {x : P'} :
  x ∈ canonical_equiv S P P' I ↔
    ∃ y ∈ I, is_localization.map P' (ring_hom.id R)
      (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) (y : P) = x :=
begin
  rw [canonical_equiv, map_equiv_apply, mem_map],
  exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩
end

@[simp] lemma canonical_equiv_symm :
  (canonical_equiv S P P').symm = canonical_equiv S P' P :=
ring_equiv.ext $ λ I, set_like.ext_iff.mpr $ λ x,
by { rw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv,
         ring_equiv.coe_mk, mem_map],
    exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ }

@[simp] lemma canonical_equiv_flip (I) :
  canonical_equiv S P P' (canonical_equiv S P' P I) = I :=
by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply]

end semiring

section is_fraction_ring

/-!
### `is_fraction_ring` section

This section concerns fractional ideals in the field of fractions,
i.e. the type `fractional_ideal R⁰ K` where `is_fraction_ring R K`.
-/

variables {K K' : Type*} [field K] [field K']
variables [algebra R K] [is_fraction_ring R K] [algebra R K'] [is_fraction_ring R K']
variables {I J : fractional_ideal R⁰ K} (h : K →ₐ[R] K')

/-- Nonzero fractional ideals contain a nonzero integer. -/
lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) :
  ∃ x ≠ (0 : R), algebra_map R K x ∈ I :=
begin
  obtain ⟨y, y_mem, y_not_mem⟩ := set_like.exists_of_lt
    (by simpa only using bot_lt_iff_ne_bot.mpr hI),
  have y_ne_zero : y ≠ 0 := by simpa using y_not_mem,
  obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y,
  refine ⟨x, _, _⟩,
  { rw [ne.def, ← @is_fraction_ring.to_map_eq_zero_iff R _ K, hx, algebra.smul_def],
    exact mul_ne_zero (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors z.2) y_ne_zero },
  { rw hx,
    exact smul_mem _ _ y_mem }
end

lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 :=
begin
  obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI,
  contrapose! x_ne_zero with map_eq_zero,
  refine is_fraction_ring.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)),
  exact ⟨algebra_map R K x, hx, h.commutes x⟩,
end

@[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 :=
⟨imp_of_not_imp_not _ _ (map_ne_zero _),
 λ hI, hI.symm ▸ map_zero h⟩

lemma coe_ideal_injective :
  function.injective (coe : ideal R → fractional_ideal R⁰ K) :=
injective_of_le_imp_le _ (λ _ _, (coe_ideal_le_coe_ideal _).mp)

@[simp]
lemma coe_ideal_eq_zero_iff
  {I : ideal R} : (I : fractional_ideal R⁰ K) = 0 ↔ I = ⊥ :=
by { rw ← coe_to_fractional_ideal_bot, exact coe_ideal_injective.eq_iff }

lemma coe_ideal_ne_zero_iff
  {I : ideal R} : (I : fractional_ideal R⁰ K) ≠ 0 ↔ I ≠ ⊥ :=
not_iff_not.mpr coe_ideal_eq_zero_iff

lemma coe_ideal_ne_zero
  {I : ideal R} (hI : I ≠ ⊥) : (I : fractional_ideal R⁰ K) ≠ 0 :=
coe_ideal_ne_zero_iff.mpr hI

end is_fraction_ring

section quotient

/-!
### `quotient` section

This section defines the ideal quotient of fractional ideals.

In this section we need that each non-zero `y : R` has an inverse in
the localization, i.e. that the localization is a field. We satisfy this
assumption by taking `S = non_zero_divisors R`, `R`'s localization at which
is a field because `R` is a domain.
-/

open_locale classical

variables {R₁ : Type*} [comm_ring R₁] {K : Type*} [field K]
variables [algebra R₁ K] [frac : is_fraction_ring R₁ K]

instance : nontrivial (fractional_ideal R₁⁰ K) :=
⟨⟨0, 1, λ h,
  have this : (1 : K) ∈ (0 : fractional_ideal R₁⁰ K) :=
    by { rw ← (algebra_map R₁ K).map_one, simpa only [h] using coe_mem_one R₁⁰ 1 },
  one_ne_zero ((mem_zero_iff _).mp this)⟩⟩

lemma ne_zero_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : I ≠ 0 :=
λ hI, @zero_ne_one (fractional_ideal R₁⁰ K) _ _ (by { convert h, simp [hI], })

variables [is_domain R₁]

include frac

lemma fractional_div_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
  is_fractional R₁⁰ (I / J : submodule R₁ K) :=
begin
  rcases I with ⟨I, aI, haI, hI⟩,
  rcases J with ⟨J, aJ, haJ, hJ⟩,
  obtain ⟨y, mem_J, not_mem_zero⟩ := set_like.exists_of_lt
    (by simpa only using bot_lt_iff_ne_bot.mpr h),
  obtain ⟨y', hy'⟩ := hJ y mem_J,
  use (aI * y'),
  split,
  { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _),
    intro y'_eq_zero,
    have : algebra_map R₁ K aJ * y = 0,
    { rw [← algebra.smul_def, ←hy', y'_eq_zero, ring_hom.map_zero] },
    have y_zero := (mul_eq_zero.mp this).resolve_left
      (mt ((algebra_map R₁ K).injective_iff.1 (is_fraction_ring.injective _ _) _)
          (mem_non_zero_divisors_iff_ne_zero.mp haJ)),
    exact not_mem_zero ((mem_zero_iff R₁⁰).mpr y_zero) },
  intros b hb,
  convert hI _ (hb _ (submodule.smul_mem _ aJ mem_J)) using 1,
  rw [← hy', mul_comm b, ← algebra.smul_def, mul_smul]
end

noncomputable instance fractional_ideal_has_div :
  has_div (fractional_ideal R₁⁰ K) :=
⟨ λ I J, if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩ ⟩

variables {I J : fractional_ideal R₁⁰ K} [ J ≠ 0 ]

@[simp] lemma div_zero {I : fractional_ideal R₁⁰ K} :
  I / 0 = 0 :=
dif_pos rfl

lemma div_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
  (I / J) = ⟨I / J, fractional_div_of_nonzero h⟩ :=
dif_neg h

@[simp] lemma coe_div {I J : fractional_ideal R₁⁰ K} (hJ : J ≠ 0) :
  (↑(I / J) : submodule R₁ K) = ↑I / (↑J : submodule R₁ K) :=
begin
  unfold has_div.div,
  simp only [dif_neg hJ, coe_mk, val_eq_coe],
end

lemma mul_one_div_le_one {I : fractional_ideal R₁⁰ K} : I * (1 / I) ≤ 1 :=
begin
  by_cases hI : I = 0,
  { rw [hI, div_zero, mul_zero],
    exact zero_le 1 },
  { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one],
    apply submodule.mul_one_div_le_one },
end

lemma le_self_mul_one_div {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) :
  I ≤ I * (1 / I) :=
begin
  by_cases hI_nz : I = 0,
  { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 },
  { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one],
    rw [← coe_le_coe, coe_one] at hI,
    exact submodule.le_self_mul_one_div hI },
end

lemma le_div_iff_of_nonzero {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) :
  I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J :=
⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx),
  λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩

lemma le_div_iff_mul_le {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) :
  I ≤ J / J' ↔ I * J' ≤ J :=
begin
  rw div_nonzero hJ',
  convert submodule.le_div_iff_mul_le using 1,
  rw [← coe_mul, coe_le_coe]
end

@[simp] lemma div_one {I : fractional_ideal R₁⁰ K} : I / 1 = I :=
begin
  rw [div_nonzero (@one_ne_zero (fractional_ideal R₁⁰ K) _ _)],
  ext,
  split; intro h,
  { simpa using mem_div_iff_forall_mul_mem.mp h 1
      ((algebra_map R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) },
  { apply mem_div_iff_forall_mul_mem.mpr,
    rintros y ⟨y', _, rfl⟩,
    rw mul_comm,
    convert submodule.smul_mem _ y' h,
    exact (algebra.smul_def _ _).symm }
end

theorem eq_one_div_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) :
  J = 1 / I :=
begin
  have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h,
  suffices h' : I * (1 / I) = 1,
  { exact (congr_arg units.inv $
      @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) },
  apply le_antisymm,
  { apply mul_le.mpr _,
    intros x hx y hy,
    rw mul_comm,
    exact (mem_div_iff_of_nonzero hI).mp hy x hx },
  rw ← h,
  apply mul_left_mono I,
  apply (le_div_iff_of_nonzero hI).mpr _,
  intros y hy x hx,
  rw mul_comm,
  exact mul_mem_mul hx hy,
end

theorem mul_div_self_cancel_iff {I : fractional_ideal R₁⁰ K} :
  I * (1 / I) = 1 ↔ ∃ J, I * J = 1 :=
⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one I J hJ]⟩

variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K']

@[simp] lemma map_div (I J : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
  (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h :=
begin
  by_cases H : J = 0,
  { rw [H, div_zero, map_zero, div_zero] },
  { apply coe_to_submodule_injective,
    simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] }
end

@[simp] lemma map_one_div (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
  (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h :=
by rw [map_div, map_one]

end quotient

section field

variables {R₁ K L : Type*} [comm_ring R₁] [is_domain R₁] [field K] [field L]
variables [algebra R₁ K] [is_fraction_ring R₁ K] [algebra K L] [is_fraction_ring K L]

lemma eq_zero_or_one (I : fractional_ideal K⁰ L) : I = 0 ∨ I = 1 :=
begin
  rw or_iff_not_imp_left,
  intro hI,
  simp_rw [@set_like.ext_iff _ _ _ I 1, fractional_ideal.mem_one_iff],
  intro x,
  split,
  { intro x_mem,
    obtain ⟨n, d, rfl⟩ := is_localization.mk'_surjective K⁰ x,
    refine ⟨n / d, _⟩,
    rw [ring_hom.map_div, is_fraction_ring.mk'_eq_div] },
  { rintro ⟨x, rfl⟩,
    obtain ⟨y, y_ne, y_mem⟩ := fractional_ideal.exists_ne_zero_mem_is_integer hI,
    rw [← div_mul_cancel x y_ne, ring_hom.map_mul, ← algebra.smul_def],
    exact submodule.smul_mem I _ y_mem }
end

lemma eq_zero_or_one_of_is_field (hF : is_field R₁) (I : fractional_ideal R₁⁰ K) : I = 0 ∨ I = 1 :=
begin
  letI : field R₁ := hF.to_field R₁,
  -- TODO can this be less ugly?
  exact @eq_zero_or_one R₁ K _ _ _ (by { unfreezingI {cases _inst_4}, convert _inst_9 }) I
end

end field

section principal_ideal_ring

variables {R₁ : Type*} [comm_ring R₁] {K : Type*} [field K]
variables [algebra R₁ K] [is_fraction_ring R₁ K]

open_locale classical

open submodule submodule.is_principal

include loc

lemma is_fractional_span_singleton (x : P) : is_fractional S (span R {x} : submodule R P) :=
let ⟨a, ha⟩ := exists_integer_multiple S x in
is_fractional_span_iff.mpr ⟨a, a.2, λ x' hx', (set.mem_singleton_iff.mp hx').symm ▸ ha⟩

variables (S)

/-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/
@[irreducible]
def span_singleton (x : P) : fractional_ideal S P :=
⟨span R {x}, is_fractional_span_singleton x⟩

local attribute [semireducible] span_singleton

@[simp] lemma coe_span_singleton (x : P) :
  (span_singleton S x : submodule R P) = span R {x} := rfl

@[simp] lemma mem_span_singleton {x y : P} :
  x ∈ span_singleton S y ↔ ∃ (z : R), z • y = x :=
submodule.mem_span_singleton

lemma mem_span_singleton_self (x : P) :
  x ∈ span_singleton S x :=
(mem_span_singleton S).mpr ⟨1, one_smul _ _⟩

variables {S}

lemma eq_span_singleton_of_principal (I : fractional_ideal S P)
  [is_principal (I : submodule R P)] :
  I = span_singleton S (generator (I : submodule R P)) :=
coe_to_submodule_injective (span_singleton_generator ↑I).symm

lemma is_principal_iff (I : fractional_ideal S P) :
  is_principal (I : submodule R P) ↔ ∃ x, I = span_singleton S x :=
⟨λ h, ⟨@generator _ _ _ _ _ ↑I h, @eq_span_singleton_of_principal _ _ _ _ _ _ _ I h⟩,
 λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton _ x)⟩ } ⟩

@[simp] lemma span_singleton_zero : span_singleton S (0 : P) = 0 :=
by { ext, simp [submodule.mem_span_singleton, eq_comm] }

lemma span_singleton_eq_zero_iff {y : P} : span_singleton S y = 0 ↔ y = 0 :=
⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y),
 λ h, by simp [h] ⟩

lemma span_singleton_ne_zero_iff {y : P} : span_singleton S y ≠ 0 ↔ y ≠ 0 :=
not_congr span_singleton_eq_zero_iff

@[simp] lemma span_singleton_one : span_singleton S (1 : P) = 1 :=
begin
  ext,
  refine (mem_span_singleton S).trans ((exists_congr _).trans (mem_one_iff S).symm),
  intro x',
  rw [algebra.smul_def, mul_one]
end

@[simp]
lemma span_singleton_mul_span_singleton (x y : P) :
  span_singleton S x * span_singleton S y = span_singleton S (x * y) :=
begin
  apply coe_to_submodule_injective,
  simp only [coe_mul, coe_span_singleton, span_mul_span, singleton_mul_singleton],
end

@[simp]
lemma coe_ideal_span_singleton (x : R) :
  (↑(ideal.span {x} : ideal R) : fractional_ideal S P) = span_singleton S (algebra_map R P x) :=
begin
  ext y,
  refine (mem_coe_ideal S).trans (iff.trans _ (mem_span_singleton S).symm),
  split,
  { rintros ⟨y', hy', rfl⟩,
    obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy',
    use x',
    rw [smul_eq_mul, ring_hom.map_mul, algebra.smul_def] },
  { rintros ⟨y', rfl⟩,
    refine ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, _⟩,
    rw [ring_hom.map_mul, algebra.smul_def] }
end

@[simp]
lemma canonical_equiv_span_singleton {P'} [comm_ring P'] [algebra R P'] [is_localization S P']
  (x : P) :
  canonical_equiv S P P' (span_singleton S x) =
    span_singleton S (is_localization.map P' (ring_hom.id R)
      (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) x) :=
begin
  apply set_like.ext_iff.mpr,
  intro y,
  split; intro h,
  { rw mem_span_singleton,
    obtain ⟨x', hx', rfl⟩ := (mem_canonical_equiv_apply _ _ _).mp h,
    obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp hx',
    use z,
    rw is_localization.map_smul,
    refl },
  { rw mem_canonical_equiv_apply,
    obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp h,
    use z • x,
    use (mem_span_singleton _).mpr ⟨z, rfl⟩,
    simp [is_localization.map_smul] }
end

lemma mem_singleton_mul {x y : P} {I : fractional_ideal S P} :
  y ∈ span_singleton S x * I ↔ ∃ y' ∈ I, y = x * y' :=
begin
  split,
  { intro h,
    apply fractional_ideal.mul_induction_on h,
    { intros x' hx' y' hy',
      obtain ⟨a, ha⟩ := (mem_span_singleton S).mp hx',
      use [a • y', submodule.smul_mem I a hy'],
      rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] },
    { exact ⟨0, submodule.zero_mem I, (mul_zero x).symm⟩ },
    { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩,
      exact ⟨y + y', submodule.add_mem I hy hy', (mul_add _ _ _).symm⟩ },
    { rintros r _ ⟨y', hy', rfl⟩,
      exact ⟨r • y', submodule.smul_mem I r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } },
  { rintros ⟨y', hy', rfl⟩,
    exact mul_mem_mul ((mem_span_singleton S).mpr ⟨1, one_smul _ _⟩) hy' }
end

omit loc

variables (K)

lemma mk'_mul_coe_ideal_eq_coe_ideal {I J : ideal R₁} {x y : R₁} (hy : y ∈ R₁⁰) :
  span_singleton R₁⁰ (is_localization.mk' K x ⟨y, hy⟩) * I = (J : fractional_ideal R₁⁰ K) ↔
  ideal.span {x} * I = ideal.span {y} * J :=
begin
  have inj : function.injective (coe : ideal R₁ → fractional_ideal R₁⁰ K) :=
    fractional_ideal.coe_ideal_injective,
  have : span_singleton R₁⁰ (is_localization.mk' _ (1 : R₁) ⟨y, hy⟩) *
           span_singleton R₁⁰ (algebra_map R₁ K y) = 1,
  { rw [span_singleton_mul_span_singleton, mul_comm, ← is_localization.mk'_eq_mul_mk'_one,
        is_localization.mk'_self, span_singleton_one] },
  let y' : units (fractional_ideal R₁⁰ K) := units.mk_of_mul_eq_one _ _ this,
  have coe_y' : ↑y' = span_singleton R₁⁰ (is_localization.mk' K (1 : R₁) ⟨y, hy⟩) := rfl,
  refine iff.trans _ (y'.mul_right_inj.trans inj.eq_iff),
  rw [coe_y', coe_ideal_mul, coe_ideal_span_singleton, coe_ideal_mul, coe_ideal_span_singleton,
    ←mul_assoc, span_singleton_mul_span_singleton, ←mul_assoc, span_singleton_mul_span_singleton,
    mul_comm (mk' _ _ _), ← is_localization.mk'_eq_mul_mk'_one,
    mul_comm (mk' _ _ _), ← is_localization.mk'_eq_mul_mk'_one,
    is_localization.mk'_self, span_singleton_one, one_mul],
end

variables {K}

lemma span_singleton_mul_coe_ideal_eq_coe_ideal {I J : ideal R₁} {z : K} :
  span_singleton R₁⁰ z * (I : fractional_ideal R₁⁰ K) = J ↔
  ideal.span {((is_localization.sec R₁⁰ z).1 : R₁)} * I =
    ideal.span {(is_localization.sec R₁⁰ z).2} * J :=
-- `erw` to deal with the distinction between `y` and `⟨y.1, y.2⟩`
by erw [← mk'_mul_coe_ideal_eq_coe_ideal K (is_localization.sec R₁⁰ z).2.prop,
        is_localization.mk'_sec K z]

variables [is_domain R₁]

lemma one_div_span_singleton (x : K) :
  1 / span_singleton R₁⁰ x = span_singleton R₁⁰ (x⁻¹) :=
if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one _ _ (by simp [h])).symm

@[simp] lemma div_span_singleton (J : fractional_ideal R₁⁰ K) (d : K) :
  J / span_singleton R₁⁰ d = span_singleton R₁⁰ (d⁻¹) * J :=
begin
  rw ← one_div_span_singleton,
  by_cases hd : d = 0,
  { simp only [hd, span_singleton_zero, div_zero, zero_mul] },
  have h_spand : span_singleton R₁⁰ d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd,
  apply le_antisymm,
  { intros x hx,
    rw [← mem_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx,
    specialize hx d (mem_span_singleton_self R₁⁰ d),
    have h_xd : x = d⁻¹ * (x * d), { field_simp },
    rw [← mem_coe, coe_mul, one_div_span_singleton, h_xd],
    exact submodule.mul_mem_mul (mem_span_singleton_self R₁⁰ _) hx },
  { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton,
    span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one],
    exact le_refl J },
end

lemma exists_eq_span_singleton_mul (I : fractional_ideal R₁⁰ K) :
  ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton R₁⁰ (algebra_map R₁ K a)⁻¹ * aI :=
begin
  obtain ⟨a_inv, nonzero, ha⟩ := I.is_fractional,
  have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero,
  have map_a_nonzero : algebra_map R₁ K a_inv ≠ 0 :=
    mt is_fraction_ring.to_map_eq_zero_iff.mp nonzero,
  refine ⟨a_inv,
          submodule.comap (algebra.linear_map R₁ K)
            ↑(span_singleton R₁⁰ (algebra_map R₁ K a_inv) * I),
          nonzero,
          ext (λ x, iff.trans ⟨_, _⟩ mem_singleton_mul.symm)⟩,
  { intro hx,
    obtain ⟨x', hx'⟩ := ha x hx,
    rw algebra.smul_def at hx',
    refine ⟨algebra_map R₁ K x', (mem_coe_ideal _).mpr ⟨x', mem_singleton_mul.mpr _, rfl⟩, _⟩,
    { exact ⟨x, hx, hx'⟩ },
    { rw [hx', ← mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } },
  { rintros ⟨y, hy, rfl⟩,
    obtain ⟨x', hx', rfl⟩ := (mem_coe_ideal _).mp hy,
    obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx',
    rw algebra.linear_map_apply at hx',
    rwa [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }
end

instance is_principal {R} [comm_ring R] [is_domain R] [is_principal_ideal_ring R]
  [algebra R K] [is_fraction_ring R K]
  (I : fractional_ideal R⁰ K) : (I : submodule R K).is_principal :=
begin
  obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I,
  use (algebra_map R K a)⁻¹ * algebra_map R K (generator aI),
  suffices : I = span_singleton R⁰ ((algebra_map R K a)⁻¹ * algebra_map R K (generator aI)),
  { exact congr_arg subtype.val this },
  conv_lhs { rw [ha, ←span_singleton_generator aI] },
  rw [ideal.submodule_span_eq, coe_ideal_span_singleton (generator aI),
      span_singleton_mul_span_singleton]
end

include loc

lemma le_span_singleton_mul_iff {x : P} {I J : fractional_ideal S P} :
  I ≤ span_singleton S x * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI :=
show (∀ {zI} (hzI : zI ∈ I), zI ∈ span_singleton _ x * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI,
by simp only [fractional_ideal.mem_singleton_mul, eq_comm]

lemma span_singleton_mul_le_iff {x : P} {I J : fractional_ideal S P} :
  span_singleton _ x * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J :=
begin
  simp only [fractional_ideal.mul_le, fractional_ideal.mem_singleton_mul,
             fractional_ideal.mem_span_singleton],
  split,
  { intros h zI hzI,
    exact h x ⟨1, one_smul _ _⟩ zI hzI },
  { rintros h _ ⟨z, rfl⟩ zI hzI,
    rw [algebra.smul_mul_assoc],
    exact submodule.smul_mem J.1 _ (h zI hzI) },
end

lemma eq_span_singleton_mul {x : P} {I J : fractional_ideal S P} :
  I = span_singleton _ x * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ ∀ z ∈ J, x * z ∈ I :=
by simp only [le_antisymm_iff, fractional_ideal.le_span_singleton_mul_iff,
              fractional_ideal.span_singleton_mul_le_iff]

end principal_ideal_ring

variables {R₁ : Type*} [comm_ring R₁]
variables {K : Type*} [field K] [algebra R₁ K] [frac : is_fraction_ring R₁ K]

local attribute [instance] classical.prop_decidable

lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal R₁⁰ K) :=
is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal R₁⁰ K)),
  by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot })

lemma is_noetherian_iff {I : fractional_ideal R₁⁰ K} :
  is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ K).fg :=
is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩

lemma is_noetherian_coe_to_fractional_ideal [_root_.is_noetherian_ring R₁] (I : ideal R₁) :
  is_noetherian R₁ (I : fractional_ideal R₁⁰ K) :=
begin
  rw is_noetherian_iff,
  intros J hJ,
  obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one),
  exact fg_map (is_noetherian.noetherian J),
end

include frac
variables [is_domain R₁]

lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal R₁⁰ K}
  (hI : is_noetherian R₁ I) :
  is_noetherian R₁ (span_singleton R₁⁰ (algebra_map R₁ K x)⁻¹ * I : fractional_ideal R₁⁰ K) :=
begin
  by_cases hx : x = 0,
  { rw [hx, ring_hom.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul],
    exact is_noetherian_zero },
  have h_gx : algebra_map R₁ K x ≠ 0,
    from mt ((algebra_map R₁ K).injective_iff.mp (is_fraction_ring.injective _ _) x) hx,
  have h_spanx : span_singleton R₁⁰ (algebra_map R₁ K x) ≠ 0,
    from span_singleton_ne_zero_iff.mpr h_gx,

  rw is_noetherian_iff at ⊢ hI,
  intros J hJ,
  rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ,
  obtain ⟨s, hs⟩ := hI _ hJ,
  use s * {(algebra_map R₁ K x)⁻¹},
  rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton R₁⁰,
      ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx,
      span_singleton_one, mul_one],
end

/-- Every fractional ideal of a noetherian integral domain is noetherian. -/
theorem is_noetherian [_root_.is_noetherian_ring R₁] (I : fractional_ideal R₁⁰ K) :
  is_noetherian R₁ I :=
begin
  obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I,
  apply is_noetherian_span_singleton_inv_to_map_mul,
  apply is_noetherian_coe_to_fractional_ideal,
end

section adjoin

include loc
omit frac

variables {R P} (S) (x : P) (hx : is_integral R x)

/-- `A[x]` is a fractional ideal for every integral `x`. -/
lemma is_fractional_adjoin_integral :
  is_fractional S (algebra.adjoin R ({x} : set P)).to_submodule :=
is_fractional_of_fg (fg_adjoin_singleton_of_integral x hx)

/-- `fractional_ideal.adjoin_integral (S : submonoid R) x hx` is `R[x]` as a fractional ideal,
where `hx` is a proof that `x : P` is integral over `R`. -/
@[simps]
def adjoin_integral : fractional_ideal S P :=
⟨_, is_fractional_adjoin_integral S x hx⟩

lemma mem_adjoin_integral_self :
  x ∈ adjoin_integral S x hx :=
algebra.subset_adjoin (set.mem_singleton x)

end adjoin

end fractional_ideal


/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.basic

/-!

# The `restrict_scalars` type alias

See the documentation attached to the `restrict_scalars` definition for advice on how and when to
use this type alias. As described there, it is often a better choice to use the `is_scalar_tower`
typeclass instead.

## Main definitions

* `restrict_scalars R S M`: the `S`-module `M` viewed as an `R` module when `S` is an `R`-algebra.
* `restrict_scalars.linear_equiv : restrict_scalars R S M ≃ₗ[S] M`: the equivalence as an
  `S`-module between the restricted and origianl space.
* `restrict_scalars.alg_equiv : restrict_scalars R S A ≃ₐ[S] A`: the equivalence as an `S`-algebra
   between the restricted and original space.

## See also

There are many similarly-named definitions elsewhere which do not refer to this type alias. These
refer to restricting the scalar type in a bundled type, such as from `A →ₗ[R] B` to `A →ₗ[S] B`:

* `linear_map.restrict_scalars`
* `linear_equiv.restrict_scalars`
* `alg_hom.restrict_scalars`
* `alg_equiv.restrict_scalars`
* `submodule.restrict_scalars`
* `subalgebra.restrict_scalars`
-/

variables (R S M A : Type*)

/-- If we put an `R`-algebra structure on a semiring `S`, we get a natural equivalence from the
category of `S`-modules to the category of representations of the algebra `S` (over `R`). The type
synonym `restrict_scalars` is essentially this equivalence.

Warning: use this type synonym judiciously! Consider an example where we want to construct an
`R`-linear map from `M` to `S`, given:
```lean
variables (R S M : Type*)
variables [comm_semiring R] [semiring S] [algebra R S] [add_comm_monoid M] [module S M]
```
With the assumptions above we can't directly state our map as we have no `module R M` structure, but
`restrict_scalars` permits it to be written as:
```lean
-- an `R`-module structure on `M` is provided by `restrict_scalars` which is compatible
example : restrict_scalars R S M →ₗ[R] S := sorry
```
However, it is usually better just to add this extra structure as an argument:
```lean
-- an `R`-module structure on `M` and proof of its compatibility is provided by the user
example [module R M] [is_scalar_tower R S M] : M →ₗ[R] S := sorry
```
The advantage of the second approach is that it defers the duty of providing the missing typeclasses
`[module R M] [is_scalar_tower R S M]`. If some concrete `M` naturally carries these (as is often
the case) then we have avoided `restrict_scalars` entirely. If not, we can pass
`restrict_scalars R S M` later on instead of `M`.

Note that this means we almost always want to state definitions and lemmas in the language of
`is_scalar_tower` rather than `restrict_scalars`.

An example of when one might want to use `restrict_scalars` would be if one has a vector space
over a field of characteristic zero and wishes to make use of the `ℚ`-algebra structure. -/
@[nolint unused_arguments]
def restrict_scalars (R S M : Type*) : Type* := M

instance [I : inhabited M] : inhabited (restrict_scalars R S M) := I

instance [I : add_comm_monoid M] : add_comm_monoid (restrict_scalars R S M) := I

instance [I : add_comm_group M] : add_comm_group (restrict_scalars R S M) := I

instance restrict_scalars.module_orig [semiring S] [add_comm_monoid M] [I : module S M] :
  module S (restrict_scalars R S M) := I

/-- `restrict_scalars.linear_equiv` is an equivalence of modules over the semiring `S`. -/
def restrict_scalars.linear_equiv [semiring S] [add_comm_monoid M] [module S M] :
  restrict_scalars R S M ≃ₗ[S] M :=
linear_equiv.refl S M

section module
variables [semiring S] [add_comm_monoid M] [comm_semiring R] [algebra R S] [module S M]

/--
When `M` is a module over a ring `S`, and `S` is an algebra over `R`, then `M` inherits a
module structure over `R`.

The preferred way of setting this up is `[module R M] [module S M] [is_scalar_tower R S M]`.
-/
instance : module R (restrict_scalars R S M) :=
module.comp_hom M (algebra_map R S)

lemma restrict_scalars_smul_def (c : R) (x : restrict_scalars R S M) :
  c • x = ((algebra_map R S c) • x : M) := rfl

@[simp] lemma restrict_scalars.linear_equiv_map_smul (t : R) (x : restrict_scalars R S M) :
  restrict_scalars.linear_equiv R S M (t • x)
  = (algebra_map R S t) • restrict_scalars.linear_equiv R S M x :=
rfl

instance : is_scalar_tower R S (restrict_scalars R S M) :=
⟨λ r S M, by { rw [algebra.smul_def, mul_smul], refl }⟩

end module

section algebra

instance [I : semiring A] : semiring (restrict_scalars R S A) := I
instance [I : ring A] : ring (restrict_scalars R S A) := I
instance [I : comm_semiring A] : comm_semiring (restrict_scalars R S A) := I
instance [I : comm_ring A] : comm_ring (restrict_scalars R S A) := I

variables [comm_semiring S] [semiring A]

instance restrict_scalars.algebra_orig [I : algebra S A] : algebra S (restrict_scalars R S A) := I

variables [algebra S A]

/-- Tautological `S`-algebra isomorphism `restrict_scalars R S A ≃ₐ[S] A`. -/
def restrict_scalars.alg_equiv : restrict_scalars R S A ≃ₐ[S] A := alg_equiv.refl

variables [comm_semiring R] [algebra R S]

/-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/
instance : algebra R (restrict_scalars R S A) :=
{ smul := (•),
  commutes' := λ r x, algebra.commutes _ _,
  smul_def' := λ _ _, algebra.smul_def _ _,
  .. (algebra_map S A).comp (algebra_map R S) }

end algebra


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

! This file was ported from Lean 3 source module data.nat.choose.bounds
! leanprover-community/mathlib commit c3291da49cfa65f0d43b094750541c0731edc932
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Algebra.GroupPower.Lemmas
import Mathbin.Algebra.Order.Field.Basic
import Mathbin.Data.Nat.Choose.Basic

/-!
# Inequalities for binomial coefficients

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

This file proves exponential bounds on binomial coefficients. We might want to add here the
bounds `n^r/r^r ≤ n.choose r ≤ e^r n^r/r^r` in the future.

## Main declarations

* `nat.choose_le_pow`: `n.choose r ≤ n^r / r!`
* `nat.pow_le_choose`: `(n + 1 - r)^r / r! ≤ n.choose r`. Beware of the fishy ℕ-subtraction.
-/

open Nat

variable {α : Type _} [LinearOrderedSemifield α]

namespace Nat

/- warning: nat.choose_le_pow -> Nat.choose_le_pow is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} [_inst_1 : LinearOrderedSemifield.{u1} α] (r : Nat) (n : Nat), LE.le.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (OrderedCancelAddCommMonoid.toPartialOrder.{u1} α (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{u1} α (LinearOrderedSemiring.toStrictOrderedSemiring.{u1} α (LinearOrderedCommSemiring.toLinearOrderedSemiring.{u1} α (LinearOrderedSemifield.toLinearOrderedCommSemiring.{u1} α _inst_1))))))) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) (Nat.choose n r)) (HDiv.hDiv.{u1, u1, u1} α α α (instHDiv.{u1} α (DivInvMonoid.toHasDiv.{u1} α (GroupWithZero.toDivInvMonoid.{u1} α (DivisionSemiring.toGroupWithZero.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))) (HPow.hPow.{u1, 0, u1} α Nat α (instHPow.{u1, 0} α Nat (Monoid.Pow.{u1} α (MonoidWithZero.toMonoid.{u1} α (Semiring.toMonoidWithZero.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1))))))) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) n) r) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) (Nat.factorial r)))
but is expected to have type
  forall {α : Type.{u1}} [_inst_1 : LinearOrderedSemifield.{u1} α] (r : Nat) (n : Nat), LE.le.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (StrictOrderedSemiring.toPartialOrder.{u1} α (LinearOrderedSemiring.toStrictOrderedSemiring.{u1} α (LinearOrderedCommSemiring.toLinearOrderedSemiring.{u1} α (LinearOrderedSemifield.toLinearOrderedCommSemiring.{u1} α _inst_1)))))) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (Nat.choose n r)) (HDiv.hDiv.{u1, u1, u1} α α α (instHDiv.{u1} α (LinearOrderedSemifield.toDiv.{u1} α _inst_1)) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) n r)) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (Nat.factorial r)))
Case conversion may be inaccurate. Consider using '#align nat.choose_le_pow Nat.choose_le_powₓ'. -/
theorem choose_le_pow (r n : ℕ) : (n.choose r : α) ≤ n ^ r / r ! :=
  by
  rw [le_div_iff']
  · norm_cast
    rw [← Nat.descFactorial_eq_factorial_mul_choose]
    exact n.desc_factorial_le_pow r
  exact_mod_cast r.factorial_pos
#align nat.choose_le_pow Nat.choose_le_pow

/- warning: nat.pow_le_choose -> Nat.pow_le_choose is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} [_inst_1 : LinearOrderedSemifield.{u1} α] (r : Nat) (n : Nat), LE.le.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (OrderedCancelAddCommMonoid.toPartialOrder.{u1} α (StrictOrderedSemiring.toOrderedCancelAddCommMonoid.{u1} α (LinearOrderedSemiring.toStrictOrderedSemiring.{u1} α (LinearOrderedCommSemiring.toLinearOrderedSemiring.{u1} α (LinearOrderedSemifield.toLinearOrderedCommSemiring.{u1} α _inst_1))))))) (HDiv.hDiv.{u1, u1, u1} α α α (instHDiv.{u1} α (DivInvMonoid.toHasDiv.{u1} α (GroupWithZero.toDivInvMonoid.{u1} α (DivisionSemiring.toGroupWithZero.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))) (HPow.hPow.{u1, 0, u1} α Nat α (instHPow.{u1, 0} α Nat (Monoid.Pow.{u1} α (MonoidWithZero.toMonoid.{u1} α (Semiring.toMonoidWithZero.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1))))))) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat Nat.hasSub) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat Nat.hasAdd) n (OfNat.ofNat.{0} Nat 1 (OfNat.mk.{0} Nat 1 (One.one.{0} Nat Nat.hasOne)))) r)) r) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) (Nat.factorial r))) ((fun (a : Type) (b : Type.{u1}) [self : HasLiftT.{1, succ u1} a b] => self.0) Nat α (HasLiftT.mk.{1, succ u1} Nat α (CoeTCₓ.coe.{1, succ u1} Nat α (Nat.castCoe.{u1} α (AddMonoidWithOne.toNatCast.{u1} α (AddCommMonoidWithOne.toAddMonoidWithOne.{u1} α (NonAssocSemiring.toAddCommMonoidWithOne.{u1} α (Semiring.toNonAssocSemiring.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))))))))) (Nat.choose n r))
but is expected to have type
  forall {α : Type.{u1}} [_inst_1 : LinearOrderedSemifield.{u1} α] (r : Nat) (n : Nat), LE.le.{u1} α (Preorder.toLE.{u1} α (PartialOrder.toPreorder.{u1} α (StrictOrderedSemiring.toPartialOrder.{u1} α (LinearOrderedSemiring.toStrictOrderedSemiring.{u1} α (LinearOrderedCommSemiring.toLinearOrderedSemiring.{u1} α (LinearOrderedSemifield.toLinearOrderedCommSemiring.{u1} α _inst_1)))))) (HDiv.hDiv.{u1, u1, u1} α α α (instHDiv.{u1} α (LinearOrderedSemifield.toDiv.{u1} α _inst_1)) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (HPow.hPow.{0, 0, 0} Nat Nat Nat (instHPow.{0, 0} Nat Nat instPowNat) (HSub.hSub.{0, 0, 0} Nat Nat Nat (instHSub.{0} Nat instSubNat) (HAdd.hAdd.{0, 0, 0} Nat Nat Nat (instHAdd.{0} Nat instAddNat) n (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))) r) r)) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (Nat.factorial r))) (Nat.cast.{u1} α (Semiring.toNatCast.{u1} α (DivisionSemiring.toSemiring.{u1} α (Semifield.toDivisionSemiring.{u1} α (LinearOrderedSemifield.toSemifield.{u1} α _inst_1)))) (Nat.choose n r))
Case conversion may be inaccurate. Consider using '#align nat.pow_le_choose Nat.pow_le_chooseₓ'. -/
-- horrific casting is due to ℕ-subtraction
theorem pow_le_choose (r n : ℕ) : ((n + 1 - r : ℕ) ^ r : α) / r ! ≤ n.choose r :=
  by
  rw [div_le_iff']
  · norm_cast
    rw [← Nat.descFactorial_eq_factorial_mul_choose]
    exact n.pow_sub_le_desc_factorial r
  exact_mod_cast r.factorial_pos
#align nat.pow_le_choose Nat.pow_le_choose

end Nat


import Mathlib

/-!
# Useful helpers

Contains the actual category class `Cat`.
-/

/-! ## Constant combinator -/

abbrev 𝕂
  {α : Sort u}
  {β : Sort v}
  (val : β)
: α → β :=
  fun _ => val

/-! ## Defining categories -/

--- A category with objects of type `Object`.
@[reducible]
class Cat
  (Object : Sort o)
  (OSem : outParam (Object → Sort osem))
  (Arrow : Object → Object → Sort a)
  (ASem : outParam (Object → Object → Sort asem))
where
  --- Arrow composition.
  compose {α β γ} :
    Arrow β γ → Arrow α β → Arrow α γ

  --- Arrow concretization.
  aConcrete :
    (A : Arrow α β) → ASem α β

  -- aConcrete_distributive
  --   {α β γ}
  --   (f : Arrow β γ)
  --   (g : Arrow α β)
  -- : aConcrete (compose f g) = compose (aConcrete f) (aConcrete g)

  --- Arrow composition is associative.
  compose_assoc {α β γ δ} (f : Arrow γ δ) (g : Arrow β γ) (h : Arrow α β) :
    aConcrete (compose f (compose g h))
    =
    aConcrete (compose (compose f g) h)

  --- Identity, careful not to shadow `id`.
  protected id {α : outParam Object} :
    Arrow α α
  --- `id ∘ f` is `f`.
  id_compose (f : Arrow α β) :
    aConcrete (compose id f) = aConcrete f
  --- `f ∘ id` is `f`.
  compose_id (f : Arrow α β) :
    aConcrete (compose f id) = aConcrete f

class Cat.Abstract
  (Object : Sort o)
  (Arrow : Object → Object → Sort a)
extends
  Cat Object (𝕂 Object) Arrow Arrow
where
  aConcrete a := a

--- Nice notation for `Cat.Arrow`, enter `\r=`.
infixr:80 " ⇒ " => Cat.Arrow
--- Usual function composition.
infixr:80 " ∘c " => Cat.compose

--- Category **0** with no objects and no arrows.
def Cat.zero : Cat.Abstract Empty (fun _ _ => Unit) where
  id :=
    by intros ; contradiction
  compose :=
    by intros ; contradiction
  compose_assoc :=
    by intros ; contradiction
  id_compose :=
    by intros ; contradiction
  compose_id :=
    by intros ; contradiction

--- Category **1** with one object and its identity arrow.
def Cat.one : Cat.Abstract Unit (fun _ _ => Unit) where
  compose _ _ :=
    ()
  compose_assoc _ _ _ :=
    rfl
  id :=
    ()
  id_compose _ :=
    rfl
  compose_id _ :=
    rfl

--- Empty structure that stores two booleans as type parameters.
---
--- This is going to be the arrow for category `Cat.two`.
@[reducible]
structure Cat.two.Arrow (b₁ b₂ : Bool)

--- Category **2** with two objects, two identity arrows, and an arrow from one object to the other.
def Cat.two : Cat.Abstract Bool two.Arrow where
  compose _ _ := {}
  compose_assoc _ _ _ :=
    rfl
  id := {}
  id_compose _ :=
    rfl
  compose_id _ :=
    rfl

--- Objects of the category **3**.
inductive Cat.three.Object
| A
| B
| C

--- Arrows of the category **3**.
structure Cat.three.Arrow (o₁ o₂ : Cat.three.Object)

--- Category **3** with three objects `A`, `B` and `C`.
---
--- Besides the three identity arrows, we have `A → B`, `B → C`, and `C → A`.
def Cat.three : Cat.Abstract three.Object three.Arrow where
  compose _ _ := {}
  compose_assoc _ _ _ :=
    rfl
  id := {}
  id_compose _ :=
    rfl
  compose_id _ :=
    rfl

--- Dual of a category.
instance Cat.Abstract.dual
  (cat : Cat.Abstract Object Arrow)
: Cat.Abstract Object (fun α β => Arrow β α) where
  compose f g :=
    cat.compose g f
  compose_assoc f g h :=
    by
      simp
      rw [cat.compose_assoc h g f]

  id := cat.id
  id_compose :=
    cat.compose_id
  compose_id :=
    cat.id_compose

--- Applying `Dual` two times yields the original.
theorem Cat.Abstract.dual_dual
  (cat : Cat.Abstract Object Arrow)
: cat.dual.dual = cat :=
  rfl

instance Cat.Prod
  (cat₁ : Cat O₁ OSem₁ A₁ ASem₁)
  (cat₂ : Cat O₂ OSem₂ A₂ ASem₂)
: Cat
  (PProd O₁ O₂)
  (fun ⟨o₁, o₂⟩ => OSem₁ o₁ × OSem₂ o₂)
  (fun ⟨α₁, α₂⟩ ⟨β₁, β₂⟩ => PProd (A₁ α₁ β₁) (A₂ α₂ β₂))
  (fun ⟨α₁, α₂⟩ ⟨β₁, β₂⟩ => PProd (ASem₁ α₁ β₁) (ASem₂ α₂ β₂))
where
  aConcrete a :=
    ⟨cat₁.aConcrete a.1, cat₂.aConcrete a.2⟩
  compose f g :=
    ⟨cat₁.compose f.1 g.1, cat₂.compose f.2 g.2⟩
  compose_assoc {α β γ δ} f g h :=
    let res : _ ∧ _ :=
      ⟨cat₁.compose_assoc f.1 g.1 h.1, cat₂.compose_assoc f.2 g.2 h.2⟩
    by
      simp [res]
  id :=
    ⟨cat₁.id, cat₂.id⟩
  id_compose f :=
    let res : _ ∧ _ :=
      ⟨cat₁.id_compose f.1, cat₂.id_compose f.2⟩
    by
      simp [res]
  compose_id f :=
    let res : _ ∧ _ :=
      ⟨cat₁.compose_id f.1, cat₂.compose_id f.2⟩
    by
      simp [res]

namespace Cat.UpArrow
  universe
    o osem
    a asem

  variable

    {Object : Sort o}
    {ASem : Object → Object → Sort asem}

    (A : Object → Object → Sort a)

  inductive Obj
    (A : Object → Object → Sort a)
  : Sort (max 1 o a)
    | mk : A α β → Obj A

  def Obj.dom : Obj A → Object
    | @Obj.mk _ _ α _β _ =>
      α
  def Obj.cod : Obj A → Object
    | @Obj.mk _ _ _α β _ =>
      β
  def Obj.get : Obj A → ((α : Object) ×' (β : Object) ×' A α β)
    | @Obj.mk _ _ α β a =>
      ⟨α, β, a⟩
  def Obj.getFun : (self : Obj A) → A self.dom self.cod
    | @Obj.mk _ _ _α _β a =>
      a

  def Obj.Concrete
    (ASem : Object → Object → Sort asem)
    (self : Obj A)
  : Sort asem :=
    ASem self.dom self.cod

  variable
    {OSem : Object → Sort osem}
    (cat : Cat Object OSem A ASem)

  structure Arrow
    (α β : Obj A)
  : Sort (max 1 o a)
  where
    a : A α.dom β.dom
    b : A α.cod β.cod
    legal :
      let f :=
        α.getFun
      let f' :=
        β.getFun
      cat.compose f' a
      =
      cat.compose b f

  def Arrow.Concrete
    (ASem : Object → Object → Sort asem)
    (α β : Obj A)
  : Sort asem :=
    ASem α.dom β.cod

  def Arrow.concrete
    (self : Arrow A (cat := cat) α β)
  : ASem α.dom β.cod :=
    let a :=
      self.a (cat := cat)
    let f' :=
      β.getFun
    cat.compose f' a
    |> cat.aConcrete

  def Arrow.compose
    {α β γ}
    (f : Arrow A cat β γ)
    (g : Arrow A cat α β)
  : Arrow A cat α γ where
    a :=
      cat.compose f.a g.a
    b :=
      cat.compose f.b g.b
    legal :=
      let legal_f := f.legal
      let legal_g := g.legal
      by
        simp at legal_f
        simp at legal_g
        simp
        sorry
end Cat.UpArrow

/-- Given `cat`, builds `cat⟶` (upperscript arrow, dunno how to unicode it). -/
instance Cat.UpArrow
  [cat : Cat O OSem A ASem]
: Cat
  (UpArrow.Obj A)
  (UpArrow.Obj.Concrete A ASem)
  (UpArrow.Arrow A cat)
  (UpArrow.Arrow.Concrete A ASem)
where
  aConcrete :=
    UpArrow.Arrow.concrete A cat

  compose :=
    by sorry
  compose_assoc :=
    by sorry

  id :=
    by sorry
  id_compose :=
    by sorry
  compose_id :=
    by sorry


import ..list.map_accum_lemmas
import .zero_length_lemmas

universe variables u

namespace vector

variable {α : Type u}
variable {n : ℕ}

local infix `++`:65 := vector.append

-- Simplify map_accumr₂ over empty lists
@[simp]
theorem map_accumr₂_nil
  {α β γ φ : Type}
  (f : α → β → γ → γ × φ)
  (x : vector α 0)
  (y : vector β 0)
  (i₀ : γ)
: map_accumr₂ f x y i₀ = (i₀, nil) :=
begin
  simp [length_zero_vector_is_nil x, length_zero_vector_is_nil y
       , nil, map_accumr₂, list.map_accumr₂],
  apply congr_arg,
  apply vector.eq,
  simp,
end

-- Simplify map_accumr₂ over appending single element to end of lists
@[simp]
theorem map_accumr₂_append1
  {n : ℕ}
  {α β γ φ : Type}
  (f : α → β → γ → γ × φ)
  (x : vector α n) (a : α)
  (y : vector β n) (b : β)
  (c : γ)
: map_accumr₂ f (x ++ cons a nil) (y ++ cons b nil) c =
  let r := f a b c in
  let z := map_accumr₂ f x y (r.fst) in
  ⟨ z.fst, z.snd ++ cons r.snd nil⟩ :=
begin
  -- Reduce to proof about list.map_accumr₂ and use corresponding theorem
  cases x with xv xp,
  cases y with yv yp,
  have len_pr : xv^.length = yv^.length, { simp [xp, yp] },
  simp [vector.cons, vector.nil, vector.append, map_accumr₂],
  simp [list.map_accumr₂_append1 f _ _ len_pr],
end

end vector


/-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.set.lattice
import order.directed
/-!
# Union lift
This file defines `set.Union_lift` to glue together functions defined on each of a collection of
sets to make a function on the Union of those sets.

## Main definitions

* `set.Union_lift` -  Given a Union of sets `Union S`, define a function on any subset of the Union
  by defining it on each component, and proving that it agrees on the intersections.
* `set.lift_cover` - Version of `set.Union_lift` for the special case that the sets cover the
  entire type.

## Main statements

There are proofs of the obvious properties of `Union_lift`, i.e. what it does to elements of
each of the sets in the `Union`, stated in different ways.

There are also three lemmas about `Union_lift` intended to aid with proving that `Union_lift` is a
homomorphism when defined on a Union of substructures. There is one lemma each to show that
constants, unary functions, or binary functions are preserved. These lemmas are:

*`set.Union_lift_const`
*`set.Union_lift_unary`
*`set.Union_lift_binary`

## Tags

directed union, directed supremum, glue, gluing
-/

variables {α ι β : Type*}

namespace set

section Union_lift

/- The unused argument `hf` is left in the definition so that the `simp` lemmas
`Union_lift_inclusion` will work without the user having to provide `hf` explicitly to
simplify terms involving `Union_lift`. -/
/-- Given a Union of sets `Union S`, define a function on the Union by defining
it on each component, and proving that it agrees on the intersections. -/
@[nolint unused_arguments]
noncomputable def Union_lift (S : ι → set α)
  (f : Π i (x : S i), β)
  (hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩)
  (T : set α) (hT : T ⊆ Union S) (x : T) : β :=
let i := classical.indefinite_description _ (mem_Union.1 (hT x.prop)) in
f i ⟨x, i.prop⟩

variables
  {S : ι → set α}
  {f : Π i (x : S i), β}
  {hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩}
  {T : set α} {hT : T ⊆ Union S} (hT' : T = Union S)

@[simp] lemma Union_lift_mk
  {i : ι} (x : S i) (hx : (x : α) ∈ T) :
  Union_lift S f hf T hT ⟨x, hx⟩ = f i x :=
let j := classical.indefinite_description _ (mem_Union.1 (hT hx)) in
by cases x with x hx; exact hf j i x j.2 _

@[simp] lemma Union_lift_inclusion {i : ι} (x : S i)
  (h : S i ⊆ T) : Union_lift S f hf T hT (set.inclusion h x) = f i x :=
Union_lift_mk x _

lemma Union_lift_of_mem
  (x : T) {i : ι} (hx : (x : α) ∈ S i) :
  Union_lift S f hf T hT x = f i ⟨x, hx⟩ :=
by cases x with x hx; exact hf _ _ _ _ _

/-- `Union_lift_const` is useful for proving that `Union_lift` is a homomorphism
  of algebraic structures when defined on the Union of algebraic subobjects.
  For example, it could be used to prove that the lift of a collection
  of group homomorphisms on a union of subgroups preserves `1`. -/
lemma Union_lift_const (c : T) (ci : Π i, S i) (hci : ∀ i, (ci i : α) = c) (cβ : β)
  (h : ∀ i, f i (ci i) = cβ) : Union_lift S f hf T hT c = cβ :=
let ⟨i, hi⟩ := set.mem_Union.1 (hT c.prop) in
have (ci i) = ⟨c, hi⟩, from subtype.ext (hci i),
by rw [Union_lift_of_mem _ hi, ← this, h]

/-- `Union_lift_unary` is useful for proving that `Union_lift` is a homomorphism
  of algebraic structures when defined on the Union of algebraic subobjects.
  For example, it could be used to prove that the lift of a collection
  of linear_maps on a union of submodules preserves scalar multiplication. -/
lemma Union_lift_unary (u : T → T) (ui : Π i, S i → S i)
  (hui : ∀ i (x : S i), u (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) x)
    = set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) (ui i x))
  (uβ : β → β)
  (h : ∀ i (x : S i), (f i (ui i x)) = uβ (f i x))
  (x : T) :
  Union_lift S f hf T (le_of_eq hT') (u x) = uβ (Union_lift S f hf T (le_of_eq hT') x) :=
begin
  subst hT',
  cases set.mem_Union.1 x.prop with i hi,
  rw [Union_lift_of_mem x hi, ← h i],
  have : x = (set.inclusion (set.subset_Union S i) ⟨x, hi⟩), { cases x, refl },
  have hx' : (set.inclusion (set.subset_Union S i) (ui i ⟨x, hi⟩) : α) ∈ S i,
    from (ui i ⟨x, hi⟩).prop,
  conv_lhs { rw [this, hui, Union_lift_inclusion] }
end

/-- `Union_lift_binary` is useful for proving that `Union_lift` is a homomorphism
  of algebraic structures when defined on the Union of algebraic subobjects.
  For example, it could be used to prove that the lift of a collection
  of group homomorphisms on a union of subgroups preserves `*`. -/
lemma Union_lift_binary (dir: directed (≤) S) (op : T → T → T) (opi : Π i, S i → S i → S i)
  (hopi : ∀ i x y, set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) (opi i x y) =
    op (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) x)
       (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) y))
  (opβ : β → β → β)
  (h : ∀ i (x y : S i), (f i (opi i x y)) = opβ (f i x) (f i y))
  (x y : T) :
  Union_lift S f hf T (le_of_eq hT') (op x y) =
    opβ (Union_lift S f hf T (le_of_eq hT') x) (Union_lift S f hf T (le_of_eq hT') y) :=
begin
  subst hT',
  cases set.mem_Union.1 x.prop with i hi,
  cases set.mem_Union.1 y.prop with j hj,
  rcases dir i j with ⟨k, hik, hjk⟩,
  rw [Union_lift_of_mem x (hik hi), Union_lift_of_mem y (hjk hj), ← h k],
  have hx : x = (set.inclusion (set.subset_Union S k) ⟨x, hik hi⟩), { cases x, refl },
  have hy : y = (set.inclusion (set.subset_Union S k) ⟨y, hjk hj⟩), { cases y, refl },
  have hxy : (set.inclusion (set.subset_Union S k) (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩) : α) ∈ S k,
    from (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩).prop,
  conv_lhs { rw [hx, hy, ← hopi, Union_lift_of_mem _ hxy] },
  simp only [coe_inclusion, subtype.coe_eta]
end

end Union_lift

variables
  {S : ι → set α}
  {f : Π i (x : S i), β}
  {hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩}
  {hS : Union S = univ}

/-- Glue together functions defined on each of a collection `S` of sets that cover a type. See
  also `set.Union_lift`.   -/
noncomputable def lift_cover
  (S : ι → set α)
  (f : Π i (x : S i), β)
  (hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩)
  (hS : Union S = univ) (a : α) : β :=
Union_lift S f hf univ (hS ▸ set.subset.refl _) ⟨a, trivial⟩

@[simp] lemma lift_cover_coe {i : ι} (x : S i) : lift_cover S f hf hS x = f i x :=
Union_lift_mk x _

lemma lift_cover_of_mem {i : ι} {x : α} (hx : (x : α) ∈ S i) :
  lift_cover S f hf hS x = f i ⟨x, hx⟩ :=
Union_lift_of_mem ⟨x, trivial⟩ hx

attribute [irreducible] Union_lift lift_cover

end set